访问js文件中的vuex存储

accessing vuex store in js file

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

import store from '../store'

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

但是它记录了一个错误:

Uncaught TypeError: Cannot read property 'getters' of undefined.

我试过了

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

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

以下对我有用:

import store from '../store'

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

在您的导入上加上括号,它应该可以工作

import { store } from '../store'
export default ( { store } ) => {
  store.getters...
}

使用这种方法对我有用:

// app.js
import store from "./store/index"

const app = new Vue({
    el: '#app',
    store, //vuex
});
window.App = app;


// inside your helper method
window.App.$store.commit("commitName" , value);

这在 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);

如果您使用的是命名空间模块,您可能会遇到我在尝试从商店检索商品时遇到的同样困难;

可能对您有用的方法是在调用 getter 时指定命名空间(示例如下)

import store from '../your-path-to-your-store-file/store.js'

console.log(store.getters.['module/module_getter']);

// for instance

console.log(store.getters.['auth/data']);

如果你使用的是 nuxt,你可以使用这种方法

window.$nuxt.$store.getters.myVar

如果您有多个模块

window.$nuxt.$store.getters['myModule/myVar']