在.js文件中访问vuex存储的状态

时间:2020-02-06 17:51:42

标签: vue.js vuejs2 vuex

auth.js

export default {
state: {
    token: localStorage.getItem('token') || null,
},
getters: {
    authToken: state => state.token,
},

store.js

import Vue from 'vue'
import Vuex from 'vuex'
import auth from './modules/auth'
Vue.use(Vuex)

export const store = new Vuex.Store({
  modules: {
    auth,
   },
})

现在,我想从任何token文件中获取.js。我尝试了以下操作,但是得到cannot read property state of undefined。如果我使用getter,则错误为cannot read property getters of undefined

config.js

import  {store}  from '../../store/store'

// const token = store.getters.authToken;
 const token = store.state.auth.token;

文件结构:

src/
   services/
           config/
              config.js
   store/
      modules/
            auth.js
      store.js

编辑:

 warning  in ./src/services/config/config.js

"export 'default' (imported as 'store') was not found in 
'../../store/store'

1 个答案:

答案 0 :(得分:0)

从2017年开始尝试使用此答案,方法简单明了。 https://stackoverflow.com/a/47819446/7617726

记住要使用默认导出