【问题标题】:How do I make reactive global property in vuejs plugin?如何在 vuejs 插件中创建反应性全局属性?
【发布时间】:2018-11-13 15:02:00
【问题描述】:

我将 $testCounter 放入一个插件中以使其全局化:

Vue.use({
  install(Vue) {
    Vue.prototype.$testCounter = 0;
    Vue.prototype.$incrementCounter = () => {
      Vue.prototype.$testCounter++;
    };
});

我想在某个组件中输出它。我还需要在全球范围内以被动方式更新它的值:

<template>
  <p>{{ $testCounter }}</p>
</template>

<script>
  mounted() {
    let comp = this;
    comp.watcherId = setInterval(() => {
      comp.$incrementCounter();

      // I want to remove this line and still be reactive :
      comp.$forceUpdate();

    }, 1000);
  }
</script>

我需要该属性具有反应性,我尝试了多种解决方案作为观察者、计算道具、vm.$set(...),但我找不到正确的方法。

【问题讨论】:

  • 你可以使用 Vuex 吗?
  • 我暂时不打算使用它,我避免为基本应用安装太多层

标签: vuejs2 vue-component vue-reactivity


【解决方案1】:

解决方案一:使用 Vuex

方案二:在根组件中设置全局响应式数据,并通过调用this.$root来使用

演示:https://jsfiddle.net/jacobgoh101/mdt4673d/2/

HTML

<div id="app">
  <test1>
      {{$root.testCounter}}

  </test1>
</div>

Javascript

Vue.component('test1', {
    template: `
  <div>
  test1
  <slot></slot>
  </div>
  `,
    mounted() {
        setInterval(() => {
            this.$root.incrementCounter();
        }, 1000)
    }
});

new Vue({
    el: "#app",
    data: {
        testCounter: 1
    },
    methods: {
        incrementCounter: function() {
            this.testCounter++;
        }
    }
})

【讨论】:

  • 您提供的示例没有在原型上定义全局道具,而是在应用程序本身的数据上定义。这是一个完全不同的情况。在原型上定义的全局 props 确实不是响应式的。
  • Vuex 的胜利
猜你喜欢
  • 1970-01-01
  • 2021-12-19
  • 1970-01-01
  • 1970-01-01
  • 2017-11-09
  • 2019-02-21
  • 2019-07-21
  • 2018-07-20
  • 2019-06-22
相关资源
最近更新 更多