将(部分)存储状态用作变异有效负载是vuex中的正确模式吗?

时间:2018-09-23 09:51:11

标签: javascript vue.js vuex flux

为了使商店待办事项列表中的布尔值发生突变,这两个突变都起作用。

export default new Vuex.Store({
	state: {
		todos: [
			{
				id: "x1",
				done: false 
			},
			{
				id: "x2",
				done: true 
			}
		]
	},
	
	mutations: {
		/** 
		 * the item in payload must is the part of the store.state that we want to mutate
		 * we will mutate the payload (not the store state) => we don't use the state parameter
		 * in order to use this mutation we must to assure that item is an object of the store state.
		 */
		setDoneWithObject(state, { item, done }) {
			//mutate the payload = mutate the store.state
			if (item) item.done = done;
		},
		
		/**
		 * give the id
		 */
		setDoneWithId(state, { id, done }) {
			//find the item in the store state
			let item = state.todos.find(o => o.id===id)
			//mutate it
			if (item) item.done = done;
		}
	}
});

  • 第一种方法更快,但需要谨慎使用,我们不能在有效负载中仅扔任何对象。

  • 第二个突变似乎更“无状态”,因此我们可以在任何上下文中轻松对其进行单元测试。它始终有效。

那么有(正确的)模式或更好的模式吗? (我的应用大量使用第一种模式)。您在这两种模式下还有其他优点/缺点吗?

0 个答案:

没有答案