vuejs 2 how to watch store values from vuex

2019-01-16 11:56发布

I am using vuex and vuejs 2 together.

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

I want to add the watch function in my vue component

This is what I have so far:

import Vue from 'vue';
import {
  MY_STATE,
} from './../../mutation-types';

export default {
  [MY_STATE](state, token) {
    state.my_state = token;
  },
};

I want to know if there are any changes in the my_state

How do I watch store.my_state in my vuejs component?

11条回答
萌系小妹纸
2楼-- · 2019-01-16 12:40

When you want to watch on state level, it can be done this way:

let App = new Vue({
    //...
    store,
    watch: {
        '$store.state.myState': function (newVal) {
            console.log(newVal);
            store.dispatch('handleMyStateChange');
        }
    },
    //...
});
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-01-16 12:41

You can also use mapState in your vue component to direct getting state from store.

In your component:

computed: mapState([
  'my_state'
])

Where my_state is a variable from the store.

查看更多
Viruses.
4楼-- · 2019-01-16 12:43

As mentioned above it is not good idea to watch changes directly in store

But in some very rare cases it may be useful for someone, so i will leave this answer. For others cases, please see @gabriel-robert answer

You can do this through state.$watch. Add this in your created (or where u need this to be executed) method in component

this.$store.watch(
    function (state) {
        return state.my_state;
    },
    function () {
        //do something on data change
    },
    {
        deep: true //add this if u need to watch object properties change etc.
    }
);

More details: https://vuex.vuejs.org/en/api.html#vuexstore-instance-methods

查看更多
对你真心纯属浪费
5楼-- · 2019-01-16 12:50

This is for all the people that cannot solve their problem with getters and actually really need a watcher, e.g. to talk to non-vue third party stuff (see Vue Watchers on when to use watchers).

Vue component's watchers and computed values both also work on computed values. So it's no different with vuex:

import { mapState } from 'vuex';

export default {
    computed: {
        ...mapState(['somestate']),
        someComputedLocalState() {
            // is triggered whenever the store state changes
            return this.somestate + ' works too';
        }
    },
    watch: {
        somestate(val, oldVal) {
            // is triggered whenever the store state changes
            console.log('do stuff', val, oldVal);
        }
    }
}

if it's only about combining local and global state, the mapState's doc also provides an example:

computed: {
    ...mapState({
        // to access local state with `this`, a normal function must be used
        countPlusLocalState (state) {
          return state.count + this.localCount
        }
    }
})
查看更多
forever°为你锁心
6楼-- · 2019-01-16 12:51

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.

查看更多
登录 后发表回答