我对vuex状态进行了以下设置:
store / index.js
import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/userAuth';
Vue.use(Vuex)
export default new Vuex.Store({
modules:{
user
}
})
./ store / modules / userAuth.js
const state = {
isCustomer: false,
isAdmin: false,
userToken: null,
};
const getters = {
//getter codes
userData: (state) => state,
};
const actions = {
async login({commit, dispatch}, data) {
//login code
},
logout({commit}) {
//logoutcode
},
autoLogout({dispatch}, milliseconds) {
//auto logout code
},
};
const mutations = {
setForAdmin: (state, status) => (state.isAdmin = status),
setForCustomer: (state, status) => (state.isCustomer = status),
setUserToken: (state, token) => (state.token = token)
};
export default {
state,
getters,
actions,
mutations,
};
我可以访问以下访问操作:
import {mapActions} from "vuex";
methods: {
...mapActions([
"login",
"logout",
"autoLogout",
"loadToken"
]),
但是我无法使用模板中的mapState
访问状态:
import {mapState} from 'vuex';
computed: {...mapState(['userToken'])}
尽管我可以通过此方法this.$store.state.user.userToken
但是要输入的字符太多。我还尝试过mapGetters
的帮助器,它们在console.log上都未定义
import {mapGetters} from 'vuex';
computed: mapGetters(["userData"]),
如何使用mapState
或mapGetters
助手访问状态数据