我同时使用vuex和vuejs 2。

我是vuex的新手,我想看一个商店变量的变化。

我想在我的vue组件中添加手表功能

这是我目前所拥有的:

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

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

我想知道my_state是否有任何变化

我怎么看店。My_state在我的vuejs组件?


当前回答

我用了这种方法,它很有效:

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
}

在你使用state from store的组件中:

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

当用户提交表单时,action STORE将被调用,创建成功后,CREATE_SUCCESS突变将被提交。Turn createsuccsuccess为true,在组件中,监控器将看到值已更改并触发通知。

isSuccess应该匹配你在geters .js中声明的名称

其他回答

如上所述,直接在商店中观察变化并不是一个好主意

但在一些非常罕见的情况下,它可能对某人有用,所以我将留下这个答案。其他情况请参见@gabriel-robert answer

你可以通过州政府,$watch。将此添加到组件中创建的(或需要执行此方法的地方)方法中

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.
    }
);

详情:https://vuex.vuejs.org/api/#watch

正如Gabriel所说,观察商店变化的最佳方法是使用mapGetters。 但在某些情况下,你不能通过mapGetters来实现,例如,你想从store中获取一些东西,使用parameter:

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

在这种情况下,你不能使用mapGetters。你可以试着这样做:

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

但不幸的是,todoById仅在以下情况下才会更新。Id改变了

如果你想更新你的组件在这种情况下使用。$store。腕表解决方案由龚提供。或者有意识地处理组件并更新它。当需要更新todoById时,使用todoById。

====== store ===== import Vue from 'vue' import Vuex from 'vuex' import axios from 'axios' Vue.use(Vuex) export default new Vuex.Store({ state: { showRegisterLoginPage: true, user: null, allitem: null, productShow: null, userCart: null }, mutations: { SET_USERS(state, payload) { state.user = payload }, HIDE_LOGIN(state) { state.showRegisterLoginPage = false }, SHOW_LOGIN(state) { state.showRegisterLoginPage = true }, SET_ALLITEM(state, payload) { state.allitem = payload }, SET_PRODUCTSHOW(state, payload) { state.productShow = payload }, SET_USERCART(state, payload) { state.userCart = payload } }, actions: { getUserLogin({ commit }) { axios({ method: 'get', url: 'http://localhost:3000/users', headers: { token: localStorage.getItem('token') } }) .then(({ data }) => { // console.log(data) commit('SET_USERS', data) }) .catch(err => { console.log(err) }) }, addItem({ dispatch }, payload) { let formData = new FormData() formData.append('name', payload.name) formData.append('file', payload.file) formData.append('category', payload.category) formData.append('price', payload.price) formData.append('stock', payload.stock) formData.append('description', payload.description) axios({ method: 'post', url: 'http://localhost:3000/products', data: formData, headers: { token: localStorage.getItem('token') } }) .then(({ data }) => { // console.log('data hasbeen created ', data) dispatch('getAllItem') }) .catch(err => { console.log(err) }) }, getAllItem({ commit }) { axios({ method: 'get', url: 'http://localhost:3000/products' }) .then(({ data }) => { // console.log(data) commit('SET_ALLITEM', data) }) .catch(err => { console.log(err) }) }, addUserCart({ dispatch }, { payload, productId }) { let newCart = { count: payload } // console.log('ini dari store nya', productId) axios({ method: 'post', url: `http://localhost:3000/transactions/${productId}`, data: newCart, headers: { token: localStorage.getItem('token') } }) .then(({ data }) => { dispatch('getUserCart') // console.log('cart hasbeen added ', data) }) .catch(err => { console.log(err) }) }, getUserCart({ commit }) { axios({ method: 'get', url: 'http://localhost:3000/transactions/user', headers: { token: localStorage.getItem('token') } }) .then(({ data }) => { // console.log(data) commit('SET_USERCART', data) }) .catch(err => { console.log(err) }) }, cartCheckout({ commit, dispatch }, transactionId) { let count = null axios({ method: 'post', url: `http://localhost:3000/transactions/checkout/${transactionId}`, headers: { token: localStorage.getItem('token') }, data: { sesuatu: 'sesuatu' } }) .then(({ data }) => { count = data.count console.log(count, data) dispatch('getUserCart') }) .catch(err => { console.log(err) }) }, deleteTransactions({ dispatch }, transactionId) { axios({ method: 'delete', url: `http://localhost:3000/transactions/${transactionId}`, headers: { token: localStorage.getItem('token') } }) .then(({ data }) => { console.log('success delete') dispatch('getUserCart') }) .catch(err => { console.log(err) }) } }, modules: {} })

你也可以订阅商店突变:

store.subscribe((mutation, state) => {
  console.log(mutation.type)
  console.log(mutation.payload)
})

https://vuex.vuejs.org/api/#subscribe

你也可以使用debouncedWatch (vue使用函数)安全地观看它

  debouncedWatch(
    lines,
    () => {
      console.log('changed');
    },
    500,
  );