vue.js - Vue3 组合 api watch 存储值

标签 vue.js vuex vuejs3 vue-composition-api

我想通过在 Vue 组件中观察它来检测 vuex 状态值的变化。我目前正在使用带有组合 API 的 vue 3。我试过这种方法:

setup(props) {
   const store = useStore();

   watch(store.getters.myvalue, function() {
      console.log('value changes detected');
   });

   return {
      myvalue: computed(() => store.getters.myvalue)
   }
},
但是在更改 myvalue 时不会调用控制台日志语句。

最佳答案

我认为您可能需要传递一个返回 myValue 的函数getter 而不是传递 myValue setter/getter 。
像这样:

setup(props) {
   const store = useStore();

   watch(()=>store.getters.myvalue, function() {
      console.log('value changes detected');
   });

   return {
      myvalue: computed(() => store.getters.myvalue)
   }
},
这是一个工作示例:

const store = Vuex.createStore({
  state() {
    return {
      count: 0
    }
  },
  getters: {
    count(state) {
      return state.count
    }
  },
  mutations: {
    increment(state) {
      state.count++
    }
  }
});

const app = Vue.createApp({
  setup() {
    const store = Vuex.useStore();

    Vue.watch(() => store.getters.count, function() {
      console.log('value changes detected');
    });

    store.watch((state, getters) => getters.count, () => {
      console.log('value changes detected via vuex watch');
    })

    return {
      myvalue: Vue.computed(() => store.getters.count),
      change: ()=>{store.commit('increment')}
    }
  }
});

app.use(store);

app.mount("#app");
<script src="https://unpkg.com/vue@3.0.3/dist/vue.global.prod.js"></script>
<script src="https://unpkg.com/vuex@4.0.0/dist/vuex.global.js"></script>

<div id="app">
  <button @click="change">💎</button>
  {{myvalue}}
</div>

然而,有更多特定于 Vuex 的方法可以做到这一点,例如使用 Vuex watch (或 subscribe)。示例和更多详细信息的链接:Watch for Vuex State changes!

关于vue.js - Vue3 组合 api watch 存储值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67775761/

相关文章:

html - <b-form-select-option> 在 Bootstrap Vue 中不起作用

vue.js - Vue 使用 mapState 计算语法错误

vue.js - 如何在vue组件中使用vuex?

navbar - Bootstrap 5 导航栏未在 Vue3 中切换

vue.js - Vue 3 中的 Fontawesome 6 throw 错误

javascript - 如何在 Vue-CLI 3 项目中全局声明 jQuery?

javascript - Vue.js 和 The Movie Database API 返回错误 403

d3.js - 无法使用 Vue.js 渲染 c3 图表

vue.js - Vue CLI 为生产环境进行了缩减,但如何缩短属性和其他定义呢?

javascript - 在 Vue.js 3 中,为什么我必须在 ref 上使用 value 属性,而不是在响应式上使用?