【问题标题】:Access the state of store or getters? _WEBPACK_IMPORTED_MODULE_3__store___.a.dispatch is not a function访问 store 或 getter 的状态? _WEBPACK_IMPORTED_MODULE_3__store___.a.dispatch 不是函数
【发布时间】:2018-04-10 01:32:27
【问题描述】:

我正在尝试验证用户是否经过身份验证以能够访问被定向的路由,否则重定向到登录路由,问题是我不知道如何从我的执行fetchUser 操作beforeEach。换句话说,我无法从路由器访问我的 getter 脚本。

store.js

import mutations from './mutations';
import actions from './actions';
import getters from './getters';

export default {
    state: {
        isLoggedIn: !!localStorage.getItem("token"),
        user_data : localStorage.getItem("user_data"),
    },
    getters ,
    mutations,
    actions
}

routes/index.js

import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

import routes from './rutas';
import store from '../store/';
const router = new VueRouter({
  mode : 'history',
  routes 
})

router.beforeEach((to, from, next) => {
   if (to.matched.some(record => record.meta.requiresAuth)) {
        if (!store.getters.isLoggedIn)  {
            next({path: '/login'})
        }
        else {
            store.dispatch('fetchUser') // Line error
            next()
        }
    } 
    else {
        next() // make sure to always call next()!
    }
})

getters.js

export default {
    isLoggedIn: state => {
        return state.isLoggedIn
    },
    user_name  : state =>{
        if(! _.isEmpty(this.user_data))
            return JSON.parse(state.user_data).name
        return '';
    },
    isEmptyUser : state =>{
        return  _.isEmpty(this.user_data);
    },
    isAdmin: state => {
        if(! _.isEmpty(this.user_data)) return state.user_data.nivel===1
        return false;
    }
}

actions.js

 export default {
 /* more methods*/

 , async fetchUser({ commit }) {
    return await axios.post('/api/auth/me')
        .then(res => {   
            setTimeout(() => {
                localStorage.setItem("user_data", JSON.stringify(res.data)); 
                Promise.resolve(res.data); 
            }, 1000);             
        },
        error => {                  
            Promise.reject(error);          
        });
}

这会在控制台中返回错误:

_WEBPACK_IMPORTED_MODULE_3__store___.a.dispatch 不是函数

我该怎么做或方法不对,我不应该直接访问操作?

【问题讨论】:

    标签: vue.js vue-router vuex


    【解决方案1】:

    问题是您的store 不是实际的存储对象,它只是用于生成它的对象。

    一个解决方案是让文件导出真实的商店:

    import Vue from 'vue';
    import Vuex from 'vuex';
    import mutations from './mutations';
    import actions from './actions';
    import getters from './getters';
    
    Vue.use(Vuex); // added here
    export default new Vuex.Store({  // changed here
        state: {
            isLoggedIn: !!localStorage.getItem("token"),
            user_data : localStorage.getItem("user_data"),
        },
        getters ,
        mutations,
        actions
    })  // changed here
    

    现在你的路由器代码可以工作了。

    您还必须注意的是,可能在您的 main.js 中的某个地方,您已经像上面那样初始化了商店。例如:

    import store from '../store/';
    new Vue({
      store: new Vuex.Store(store),
      // ...
    })
    

    现在您必须删除该初始化并直接使用存储:

    import store from '../store/';
    new Vue({
      store: store, // or simply store
      // ...
    })
    

    一切都应该很好。

    【讨论】:

    • 在 Vue 的实例中,我有 store: new Vuex.Store (store),如上所述,但是当我这样做时,我在创建商店实例之前收到错误调用 Vue.use (Vuex)。如果我做典型的Vue.use (Vuex) 我得到错误 getters should be function but "getters.isLoggedIn" is true
    • 您能在问题中粘贴您的 getters 声明吗?
    • 您在更改之前是否收到该错误?之前一切正常,但路由器除外?
    • 它现在工作正常,只是一个简短的问题,是否可以在 mapState 中添加一个 getter?我现在在数据中添加了一个新字段并抓取username : this.$store.getters.user_name,
    • 我假设您使用 mapState 从状态创建计算属性。同样,您可以使用 mapGetters 从 getter 创建计算属性。是这样吗?
    猜你喜欢
    • 2018-12-12
    • 1970-01-01
    • 2021-07-06
    • 2019-03-21
    • 2023-03-18
    • 2021-08-27
    • 2016-09-29
    • 2019-11-17
    • 2021-08-23
    相关资源
    最近更新 更多