Vuejs2 如何在vuejs插件中创建被动全局属性?

Vuejs2 如何在vuejs插件中创建被动全局属性?,vuejs2,vue-component,vue-reactivity,Vuejs2,Vue Component,Vue Reactivity,我将$testCounter放在一个插件中,使其成为全球性的: Vue.use({ install(Vue) { Vue.prototype.$testCounter = 0; Vue.prototype.$incrementCounter = () => { Vue.prototype.$testCounter++; }; }); 我想在某个组件中输出它。我还需要对其价值进行全球更新,并作出反应: <template> <p

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

{{$testCounter}}

安装的(){ 让comp=这个; comp.watcherId=setInterval(()=>{ 组件$incrementCounter(); //我想删除这条线路,但仍然是被动的: 组件$forceUpdate(); }, 1000); }

我需要属性是被动的,我尝试了一个多个解决方案作为观察者、计算道具、vm.$set(…),但我找不到正确的方法来执行此操作。

解决方案1:使用Vuex

解决方案2:在根组件中设置全局反应数据,并通过调用
this来使用它。$root

演示:

HTML


{{$root.testCounter}
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++;
        }
    }
})
Vue.component('test1'{
模板:`
测试1
`,
安装的(){
设置间隔(()=>{
这是。$root.incrementCounter();
}, 1000)
}
});
新Vue({
el:“应用程序”,
数据:{
测试计数器:1
},
方法:{
递增计数器:函数(){
testCounter++;
}
}
})

您可以使用Vuex?我现在不打算使用它,我避免为基本应用程序安装太多层。您提供的示例没有在原型上定义全局道具,而是在应用程序本身的数据上定义全局道具。这是完全不同的情况。原型上定义的全局道具确实不是被动的。Vuex代表胜利
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++;
        }
    }
})