我同时使用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中声明的名称
这是为所有的人,不能解决他们的问题与getter,实际上真的需要一个监视器,例如,与非Vue第三方的东西(见Vue监视器何时使用监视器)。
Vue组件的监视器和计算值也都适用于计算值。所以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);
}
}
}
如果只是结合本地和全局状态,mapState的文档也提供了一个例子:
computed: {
...mapState({
// to access local state with `this`, a normal function must be used
countPlusLocalState (state) {
return state.count + this.localCount
}
}
})
你不应该使用组件的监视器来监听状态的变化。我建议您使用getter函数,然后在组件中映射它们。
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters({
myState: 'getMyState'
})
}
}
在你的店里:
const getters = {
getMyState: state => state.my_state
}
您应该能够通过使用此功能侦听对您的商店所做的任何更改。myState在你的组件。
https://vuex.vuejs.org/en/getters.html#the-mapgetters-helper
正如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。