vue.js 2 how to watch store values from vuex

后端 未结 18 2269
傲寒
傲寒 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 11:08

    I used this way and it works:

    store.js:

    const state = {
      createSuccess: false
    };
    

    mutations.js

    [mutations.CREATE_SUCCESS](state, payload) {
        state.createSuccess = payload;
    }
    

    actions.js

    async [mutations.STORE]({ commit }, payload) {
      try {
        let result = await axios.post('/api/admin/users', payload);
        commit(mutations.CREATE_SUCCESS, user);
      } catch (err) {
        console.log(err);
      }
    }
    

    getters.js

    isSuccess: state => {
        return state.createSuccess
    }
    

    And in your component where you use state from store:

    watch: {
        isSuccess(value) {
          if (value) {
            this.$notify({
              title: "Success",
              message: "Create user success",
              type: "success"
            });
          }
        }
      }
    

    When user submit form, action STORE will be call, after created success, CREATE_SUCCESS mutation is committed after that. Turn createSuccess is true, and in component, watcher will see value has changed and trigger notification.

    isSuccess should be match with the name you declare in getters.js

提交回复
热议问题