Vue3 组合 api 看存储值

Vue3 composition api watch store value

我想通过在 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改变时不会调用控制台日志语句。

我认为您可能需要传递 returns myValue getter 的函数,而不是传递 myValue 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)。 Link 示例和更多详细信息:Watch for Vuex State changes!

让我笼统地回答你的问题。

首先,您需要创建包含状态、getter、操作和变更的存储。

作文API

您需要通过

在组件内部导入商店
import { useStore } from 'vuex';

并像这样在组件内部初始化它:

export default {
 setup(){
  const store = useStore();
 }
}

为了观察商店的变化,你可以使用 watchEffect(),不要忘记导入它

import { watchEffect } from '@vue/runtime-core';

watchEffect(() => {
  // pretend you have a getData getter in store
  const data = store.getters.getData;
  if(data === null) return;
  console.log(data);
})

此外,您可以使用 watch(),这是一种较旧的方法

import { watch } from '@vue/runtime-core';

watch(
  // pretend you have a getData getter in store
  () => store.getters.getData,
  (val, oldVal) => console.dir({ val, oldVal})
)

在某些情况下,您会在控制台中收到这样的警告

Invalid watch source:  null A watch source can only be a getter/effect function, a ref, a reactive object, or an array of these types. 

`watch(fn, options?)` signature has been moved to a separate API. Use `watchEffect(fn, options?)` instead. `watch` now only supports `watch(source, cb, options?) signature. 

选项API

观察商店变化的经典方法是创建这样的函数

data(){
 return {
  todo: null
 }
},
methods: {
 watchStore(){
  this.$store.watch(
    () => this.$store.getters.getData,
    data => this.todo = data
  )
 }
},
mounted(){
 this.watchStore();
}