[英]Vuex state module structure
I adopted the file structure on vuex with modules. 我在带有模块的vuex上采用了文件结构。 Originally I just had everything in one store file (I don't know what I was thinking).
最初,我只是将所有内容存储在一个存储文件中(我不知道自己在想什么)。 Now that I refactored the code to a better more maintainable structure I am having issues with how to mimic the state that I had before.
现在,我将代码重构为更好的可维护性结构,我在如何模仿以前的状态方面遇到了问题。
My previous state for the user field was just a user object like this: 我以前对用户字段的状态只是一个用户对象,如下所示:
user: {...}
Now that I used this format 现在,我使用了这种格式
const state = {
}
const mutations = {
fetchUser(state,user){
console.log(user)
state = user;
}
};
const actions = {
currentUser: ({commit}) => {
axios.get('/user').then(response => {
if(response.status == 200){
commit('fetchUser', response.data.data);
}
}).catch(response => {
});
}
}
My state translates to : 我的状态转换为:
user:{}
with an empty object. 与一个空的对象。 Shouldn't this assign the user into that user state object or am I missing something.
这不应该将用户分配到该用户状态对象中,还是我丢失了某些内容。
Inside a module's mutations and getters, the first argument received will be the module's local state.
在模块的变量和获取器内部,收到的第一个参数将是模块的本地状态。
So your mutation should access the module object: 因此,您的变异应访问模块对象:
const mutations = {
setUser(state, user){
state.user = user; // Assuming you have a user module **
}
};
** Assuming you have a user module this way: **假设您具有这种方式的用户模块:
const store = new Vuex.Store({
modules: {
user: moduleUser,
// more modules ...
}
})
Mutations should only modified the state. 突变只能修改状态。 You should change your logic to fetch user data from an action only and not from your mutation itself, for example:
您应该更改逻辑以仅从操作而不是从突变本身获取用户数据,例如:
const actions = {
currentUser: ({commit}) => {
axios.get('/user').then(response => {
if(response.status == 200){
var response = response.data.data;
commit('setUser', response);
}
}).catch(response => {
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.