【问题标题】:accessing vuex store in js file访问 js 文件中的 vuex 存储
【发布时间】:2018-05-28 21:26:22
【问题描述】:

就像在 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

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

【问题讨论】:

  • 我已经看到一些由于旧语法和新版本的相关问题。我认为给出的答案已在最新版本中检查。
  • 写一个以store getter 作为函数参数的纯函数怎么样?然后在 Vue 组件中使用时将 store 传递给函数

标签: javascript vue.js vuex


【解决方案1】:

以下内容对我有用:

import store from '../store'

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

【讨论】:

  • 商店未定义
  • 它对我有用。刚刚在我的回购中尝试过。是的,如果您访问 Vue 之外的商店,则必须使用 getters
  • 是的,只是看着它,它应该可以工作,但由于一些非常奇怪的原因它不能工作。
  • 我会仔细检查您的项目中store.js 的路径是否正确。
  • 这可能会导致意外行为。例如对我来说,当用户第一次登录时,这只会在 .js 文件中产生 undefined,但 Vuex 显示它已明确定义。
【解决方案2】:

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

import { store } from '../store'

【讨论】:

  • 为什么要加括号?它有一个默认导出。
【解决方案3】:
export default ( { store } ) => {
  store.getters...
}

【讨论】:

    【解决方案4】:

    使用这种方法对我有用:

    // 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);
    

    【讨论】:

      【解决方案5】:

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

      【讨论】:

        【解决方案6】:

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

        您可能会在调用 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']);
        

        【讨论】:

        • javascript console.log(store.getters) // returns all getters from vuex, may help while debugging.
        • 这对我有用:store.getters['auth/data']。吸气剂后没有“句号”
        猜你喜欢
        • 2021-06-17
        • 2020-05-20
        • 2022-08-19
        • 1970-01-01
        • 2018-11-10
        • 2021-08-10
        • 2021-12-12
        • 1970-01-01
        • 2023-03-28
        相关资源
        最近更新 更多