【问题标题】:state not define in vue状态未在 vue 中定义
【发布时间】:2018-08-17 18:15:00
【问题描述】:

大家好,我关注的一切都没有提供谷歌,但这些都不是我的代码下面的 vuex 3.0.1 和 vue 2.5 的新手

import Vue from 'vue'
import App from './App'
import router from './router'
import axios from 'axios'
import store from './store'

Vue.prototype.$http = axios;


 var VueResource = require('vue-resource');
 Vue.use(VueResource);


   router.beforeEach((to, from, next) => {
     console.log(this.$store.state.authUser)// this is not working
      if (to.matched.some(record => record.meta.requiresAuth) && 
        (!this.$store.state.authUser || 
  this.$store.state.authUser === 'null')){
  const authUser = localStorage.getItem('authUser')
   console.log('here log');
   next({ path: '/', })

 }else{
   console.log('bhar else redirect');
  next()  
 }

});
 new Vue({
   el: '#app',
    router,
    store,
   template: '<App/>',

    components: {
     App
     }
 })

如果我删除这个 this.$store.state.authUser 一切都会正常工作,这是我的 store.js 文件

import Vue from 'vue'
 import Vuex from 'vuex'
 import userStore from './user/userStore.js'
 Vue.use(Vuex)
  const debug = process.env.NODE_ENV !== 'production'

 export default new Vuex.Store({
  modules:{
    userStore
  },

 strict:debug
 })

这是我的用户商店

 const state = {
   authUser:null
    }
const mutations  = {
    SET_AUTH_USER(state,userObj){
        state.authUser = userObj
        }
 }
   const actions = {
    setUserObject :({commit},userObj) =>{
        commit('SET_AUTH_USER',userObj)
     }
   }
  export default {
      state, mutations, actions
 }

这是我的登录成功,我尝试在商店中发送价值注意我在商店中有价值

  this.$store.dispatch('setUserObject',response.data.id)

我一切正常,但不知道为什么会抛出错误无法读取未定义的属性“状态”

【问题讨论】:

    标签: vue.js vuex


    【解决方案1】:

    您正在使用this.$store 在路由器的beforeEach 保护中访问您的商店。但是this不是你的vue实例,也没有$store属性。

    由于您使用import store from './store' 导入商店,因此您可以使用store 导入来访问您的商店,如下所示:

    router.beforeEach((to, from, next) => {
         console.log(store.state.userStore.authUser)// this will log put authUser from userStore module
          if (to.matched.some(record => record.meta.requiresAuth) && 
            (!store.state.userStore.authUser || 
      store.state.userStore.authUser === 'null')){
      const authUser = localStorage.getItem('authUser')
       console.log('here log');
       next({ path: '/', })
    
     }else{
       console.log('bhar else redirect');
      next()  
     }
    
    });
    

    authUser 属性属于 userStore 模块,因此要访问它,请使用

    store.state.userStore.authUser
    

    【讨论】:

    • 谢谢我还有一个问题,如何在 router.beforeeach 中设置 axios 标头
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-22
    • 2020-11-15
    • 2018-04-21
    • 1970-01-01
    • 2020-05-09
    • 2018-08-09
    • 2020-06-15
    相关资源
    最近更新 更多