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

标签 vuejs2 vue-component vue-reactivity

我将 $testCounter 放在一个插件中使其成为全局的:

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

我想在某个组件中输出它。我还需要它的值(value)在全局范围内被动更新:

<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>

我需要该属性是 react 性的,我尝试了多个解决方案作为观察者、计算 Prop 、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++;
        }
    }
})

关于vuejs2 - 如何在 vuejs 插件中创建响应式全局属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50677826/

相关文章:

javascript - Vue.js 事件目标为空?

javascript - Vue.js 中计算属性和普通数据的区别

javascript - Vue-google-map 自动完成两种方式绑定(bind)不起作用

vuejs2 - $router.replace() 不更新浏览器查询字符串

javascript - document.elementFromPoint(x, y) 未报告正确的子元素

javascript - 如何从 Javascript 生成 Vue 组件

javascript - 如何在存储在数组中的 html vue js 中提供编辑功能?

vue.js - ref、toRef 和 toRefs 之间有什么区别

typescript - 如何将 react 数据传递给 Vue 3 中的可组合对象

javascript - 单击时滚动到 <li> 并溢出(javascript)