【问题标题】:How to access Vuex store in helper functions?如何在辅助函数中访问 Vuex 商店?
【发布时间】:2017-12-05 19:08:03
【问题描述】:

对于通过 api_token 进行的 vue-axios 身份验证,我使用帮助文件 api.js。

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

我认为 api.js 助手没有看到全局存储 - Vuex $store。

在其他组件中我不需要导入 Vuex 存储,他可以在应用程序的任何地方使用。

如何在 helper 中使用 this.$storage?

//api.js 
import axios from 'axios'

let api_token = this.$store.getters.get_api_token  //got error!


export function get(url) {
    return axios({
        method: 'GET',
        url: url,
        headers: {
            'Authorization': `Bearer ${api_token}`
        }
    })
}

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

Vue.use(Vuex);

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

    },
    getters: {
        get_api_token(state){
            return state.api_token
        }
    },
});

export default store


//App.vue
import {get} from './helpers/api';
export default {

    created() {
        get(`/api/user/${1}`)
            .then((res) => {
                ///do it
            })
            .catch((err) => {
                console.log(err);
            })

    }
}

【问题讨论】:

    标签: javascript vuejs2 vuex


    【解决方案1】:

    找到答案

    // some JS file
    import store from './../store'; // path to your Vuex store
    
    let user = store.getters.user;
    // do stuff with user
    

    https://laracasts.com/discuss/channels/vue/vuex-accessing-vuex-outside-of-a-vue-component

    【讨论】:

    • 问题是从架构的角度来看是正确的。
    • 当我这样做时,我得到了一个代理对象
    猜你喜欢
    • 1970-01-01
    • 2021-09-24
    • 1970-01-01
    • 2020-12-07
    • 2021-10-20
    • 2020-10-01
    • 2019-01-17
    • 2018-05-19
    • 2018-12-19
    相关资源
    最近更新 更多