vue.js 2 how to watch store values from vuex

后端 未结 18 2228
傲寒
傲寒 2020-11-27 10:26

I am using vuex and vuejs 2 together.

I am new to vuex, I want to watch a store variable change.

I want t

18条回答
  •  一生所求
    2020-11-27 10:48

    The best way to watch store changes is to use mapGetters as Gabriel said. But there is a case when you can't do it through mapGetters e.g. you want to get something from store using parameter:

    getters: {
      getTodoById: (state, getters) => (id) => {
        return state.todos.find(todo => todo.id === id)
      }
    }
    

    in that case you can't use mapGetters. You may try to do something like this instead:

    computed: {
        todoById() {
            return this.$store.getters.getTodoById(this.id)
        }
    }
    

    But unfortunately todoById will be updated only if this.id is changed

    If you want you component update in such case use this.$store.watch solution provided by Gong. Or handle your component consciously and update this.id when you need to update todoById.

提交回复
热议问题