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



我把$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:使用 Vuex

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

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

.HTML

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

爪哇语

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++;
}
}
})

最新更新