我有一个关于动作和突变的问题。
我有一个带有以下路由的 Web API 后端:getProducts(返回所有产品)和 addProduct、deleteProduct、updateProduct,它只返回成功或失败。
在前端,在特定模块状态下,我有兴趣保留所有产品的列表。
state.js:
export default () => ({
products: [],
});
下一个方法有多错误?
我没有在 addProduct(将新产品推送到状态)、updateProduct(编辑状态)和 deleteProduct(拼接状态)操作上提交突变,而是用我已经在数据库中添加/更新/删除的内容“刷新”我的状态,调度 getProducts 操作,这是唯一提交突变的操作。
通过这种方式,我的状态始终与“单一事实来源”(数据库数据)保持同步,并且我还在并发的选项卡/计算机/浏览器请求上保持状态是最新的。
动作.js:
getProducts({commit}) {
const route = `products/todo`;
return axios.get(route)
.then(response => {
commit('SET_PRODUCTS', response.data);
})
.catch(err => {
//....
})
},
addProduct({dispatch}, data) {
const route = `products/todo`;
return axios.post(route, data)
.then((response) => {
return dispatch('getProducts').then(() => {
//....
})
})
.catch(err => {
//...
})
},
deleteProduct({dispatch}, data) {
const route = `products/todo`;
return axios.delete(route)
.then(() => {
return dispatch('getProducts').then(() => {
//..........
})
})
.catch(err => {
//......
})
},
updateProduct({dispatch}, data) {
const route = `products/todo`;
return axios.put(route, data)
.then(response => {
return dispatch('getProducts').then(() => {
//...
})
})
.catch(err => {
//...
})
},
//mutations.js
export default {
SET_PRODUCTS: (state, data) => {
state.products = data;
},
}
这是一个错误的方法吗?如果我选择这样编写动作和突变,是否会错误地使用 VUEX 的状态管理?