我已经设置了一个 Vuex 商店,以便在不同的组件之间共享状态。一位同事不小心在 Vuex 存储上设置了一个新属性,而没有分派动作或提交突变,但没有崩溃,应用程序继续运行。有没有办法防止这种情况发生?
这是商店的结构(简化):
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
options: {},
},
actions: {
setAttributes (context, payload) {
context.commit('setAttributes', payload);
},
setPrice (context, payload) {
context.commit('setPrice', payload);
}
},
mutations: {
setAttributes (state, payload) {
state.options.width = payload.width;
state.options.height = payload.height;
},
setPrice (state, payload) {
state.options.price = payload.price;
},
},
getters: {
options: state => {
return state.options
}
}
});
这是 Vue 实例的结构:
import Vue from 'vue';
import { mapGetters } from 'vuex';
import { store } from './store/store';
new Vue({
el: '#app',
store,
computed: {
...mapGetters([
'options',
])
},
mounted() {
this.$store.dispatch('setAttributes', {
width: 100,
height: 80,
});
}
});
为了改变价格,我会做这样的事情:
this.$store.dispatch('setPrice', {
price: 800,
});
但我们发现这也是可能的:
this.options.price = 800;
有没有办法阻止它,或者我们应该避免在共享状态下使用嵌套对象?
30秒到达战场
相关分类