场景:
在 user.js
我有:
import * as mutationTypes from "../mutation-types";
import {user} from "./user_data";
export const state = {
user: user
...
}
export const getters = {
user: (state) => state.user,
...
};
export const mutations = {
[mutationTypes.SET_USER]: (state, payload) => {
state.user=payload;
},
...
);
export const actions = {
setUser: ({ commit }, payload) => {
commit(mutationTypes.SET_USER, payload);
},
...
);
export default {
state,
getters,
mutations,
actions,
};
现在我想将在几个页面中使用的方法从 .vue 页面移动到这个商店页面: 所以我在 user.js 操作中添加了以下内容:
getUser: async ({ commit }) =>{
this.user.loading=true;
try{
const res = await this.$http.post('/ajax/settings/settings_read.php');
if (res.data.errorid=='0')
{
let payload=res.data.user;
commit(mutationTypes.SET_USER, payload);
}
else
{
this.$router.push('/auth/login').catch(() => {});
}
} catch(e)
{
console.log(e);
}
this.user.loading=false;
},
在 .vue 页面中(实际上我尝试了可能不同的解决方案在几个地方添加 async/await)
import { mapActions } from "vuex";
...
created(){
this.$store.dispatch("getUser");
},
但不起作用。
可以建议将方法移动到 vuex 存储的正确方法吗?
答案 0 :(得分:0)
看起来 this.user 是对您所在州的用户的引用,因此
this.user.loading=true;
会改变突变之外的状态。