【问题标题】:accessing vuex store's state in .js file在 .js 文件中访问 vuex 商店的状态
【发布时间】:2020-05-22 20:22:37
【问题描述】:

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,
   },
})

现在我想从任何.js 文件中获取token。我尝试如下,但我得到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'

【问题讨论】:

  • 该错误意味着您没有正确导入store 对象,因此它解析为undefined。你确定路径是../../store/store?你确定那个config.js 文件是什么引发了错误?
  • @thanksd 我确定路径是正确的,错误来自config.js,我添加了一些warnings
  • 嗯,那么不确定。虽然我希望 export 'default' (imported as 'store') 错误只有在您尝试通过 import store from ... 导入时才会发生。

标签: vue.js vuejs2 vuex


【解决方案1】:

试试这个 2017 年的答案,它简单明了。 https://stackoverflow.com/a/47819446/7617726

记得使用默认导出

【讨论】:

    猜你喜欢
    • 2018-05-19
    • 1970-01-01
    • 2023-03-28
    • 2021-09-24
    • 1970-01-01
    • 2019-02-08
    • 2017-07-06
    • 2021-04-10
    • 1970-01-01
    相关资源
    最近更新 更多