我正在尝试使用Vuex处理全局变量,但即使我使用undefined
初始化Vuex
,我仍然会出现Vue.use();
错误。
TypeError: Cannot read property 'isAuth' of undefined
store.js:
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
isAuth: true,
});
main.js:
import store from './store/store';
....
new Vue({
el: '#app',
store,
router,
render: h => h(App),
.......
我致电isAuth
查看其值如下:this.$store.isAuth;
这会导致undefined
错误。
我在Vuex
中初始化了store.js
,但仍然遇到undefined
错误。有什么我想念的吗?
答案 0 :(得分:3)
At a guess, this might work with what you're currently doing: this.$store.state.isAuth
but I would do it like below.
I've not used the store in the way you have before but haven't had issues when using modules, try like this:
// authModule.js
const state = {
isAuth: true
}
const getters = {
getIsAuth (state) {
return state.isAuth
}
}
export default {
state,
getters
}
Then register it like so:
import authModule from './modules/authModule'
export default new Vuex.Store({
modules: {
authModule
}
})
Then on your vue instance:
import {mapGetters} from 'vuex'
computed: {
...mapGetters({
isAuth: 'getIsAuth'
})
}
You can now access via this.isAuth
. You can also access like: this.$store.state.authModule.isAuth
This is actually best practice according to their docs as it keeps things tidy when the project gets larger.