如何在 vuejs 插件中制作反应式全局 属性?

How do I make reactive global property in vuejs plugin?

我将 $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

方案二:在根组件中设置全局响应数据,调用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++;
        }
    }
})