如何在vuejs插件中创建响应式全局属性?

时间:2018-06-04 09:52:25

标签: vuejs2 vue-component vue-reactivity

我将$ 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(...),但我找不到正确的方法来做到这一点。

1 个答案:

答案 0 :(得分:2)

解决方案1 ​​:使用Vuex

解决方案2 :在根组件中设置全局响应数据,并通过调用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++;
        }
    }
})
相关问题