从模板访问vuex状态数据

时间:2020-08-29 14:13:39

标签: vue.js vuejs2 vue-component vuex

我对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"]),

如何使用mapStatemapGetters助手访问状态数据

0 个答案:

没有答案