【发布时间】:2021-02-23 15:24:57
【问题描述】:
我为此发疯了,因为我无法理解我可能会丢失什么......所以我基本上使用 vuex 来存储用户的状态。我已经设置了一条路由并使用 Axios 调用此路由以从用户那里检索一些信息。我可以在 vue 开发工具中看到状态和所有内容都已设置,我只是很难访问它。如果我在mounted中执行以下console.log(this.$store.state.baseSettings),则显示如下:
现在我想通过将 .user 添加到该 console.log 中,我会得到我需要的东西,但它显示的是一个空对象。
我还尝试了以下方法:
computed: {
user() {
return this.$store.state.baseSettings.user;
},
},
如果我在模板本身中执行 {{ user }},则此方法有效,但如果我尝试在计算、安装或任何方法中访问 this.user,我也会得到一个空对象。这有什么原因吗?我在这里遗漏了一些简单/明显的东西吗?
任何帮助将不胜感激!这是我的完整代码:
app.js:
import Vue from 'vue';
import Vuetify from 'vuetify';
import router from '../../router';
import store from './store';
import {userComputed, settingsMethods} from './store/helpers';
import App from '../App.vue';
new Vue({
router,
store,
vuetify: new Vuetify(),
render: h => h(App),
computed: {
...userComputed,
},
methods: {
...settingsMethods,
},
mounted() {
return this.getAllSettings();
},
}).$mount('#app');
App.vue
<template>
<v-app>
{{ user }}
<v-main :class="!user ? 'background-img' : null">
<v-container fluid>
<nav-bar/>
<router-view/>
</v-container>
</v-main>
</v-app>
</template>
<script>
export default {
computed: {
user() {
// Works but only in above <template></template>
return this.$store.state.baseSettings.user;
},
},
mounted() {
// Returns object with user data (see screenshot).
console.log(this.$store.state.baseSettings);
// Empty object!
console.log(this.$store.state.baseSettings.user);
// Empty object
console.log(this.user)
}
}
</script>
baseSettings.js:
const state = {
user: {},
};
const getters = {
getUser: state => _.keys(state.user),
};
const actions = {
getAllSettings({ commit }) {
return axios.get('settings').then(baseSettings => {
commit('setUser', _.get(baseSettings, 'data.user', {}));
});
},
};
const mutations = {
setUser(state, user) {
state.user = user;
},
};
export default {
namespaced: true,
state,
getters,
actions,
mutations,
};
helpers.js:
import { mapActions, mapState } from 'vuex';
export const userComputed = {
...mapState('baseSettings', ['user']),
};
export const settingsMethods = {
...mapActions('baseSettings', ['getAllSettings']),
};
index.js
import Vue from 'vue';
import Vuex from 'vuex';
import baseSettings from '../modules/baseSettings';
Vue.use(Vuex);
const debug = process.env.NODE_ENV !== 'production';
export default new Vuex.Store({
modules: {
baseSettings,
},
strict: debug,
});
非常感谢!
【问题讨论】:
-
您很可能会遇到此
baseSettings数据尚未完成处理/完全获取的竞争条件。仅仅因为您尝试在mounted钩子中查询数据,并不一定意味着数据已经准备就绪,除非您在同一个钩子上执行了 Axios 请求,并且在访问数据之前通过await完成了它。