访问 js 文件中的 vuex 存储

新手上路,请多包涵

就像在 main.js 中一样,我正在尝试从辅助函数文件访问我的商店:

 import store from '../store'

let auth = store.getters.config.urls.auth

但它会记录一个错误:

未捕获的类型错误:无法读取未定义的属性“getters”。

我努力了

this.$store.getters.config.urls.auth

结果相同。

店铺:

 //Vuex
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);

const store = new Vuex.Store({
    state: {
        config: 'config',

    },
    getters: {
        config: state => state.config
    },
});

export default store

如何使我的商店在组件之外可用?

原文由 Elena Maximova 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 728
2 个回答

以下对我有用:

 import store from '../store'

store.getters.config
// => 'config'

原文由 Paweł Gościcki 发布,翻译遵循 CC BY-SA 3.0 许可协议

这在 2021 年对我有用

我尝试了很多不同的东西,至少在 Vue 3 中,这似乎可行。这是一个示例商店:

 export default {
  user: {
    bearerToken: 'initial',
  },
};

这是我的 Getters 文件:

 export default {
  token: (state) => () => state.user.bearerToken,
};

在您的 .js 文件中,将页面添加到您的 store\index.js 文件中。

 import store from '../store';

为了访问 getter,只需记住它是一个函数(当您使用 mapGetters 时可能看起来不同。)

 console.log('Checking the getters:', store.getters.token());

状态更直接:

 console.log('Checking the state:', store.state.user.bearerToken);

原文由 Grandizer 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题