Javascript 如何访问Vuex store in helper函数?
对于vue axios auth by api_令牌,我使用帮助文件api.js 我得到错误-UncaughtTypeError:无法读取未定义的属性“getters” 我认为api.js helper没有看到全局存储—Vuex$store 在其他组件中,我不需要导入Vuex存储,他可以在应用程序的任何位置使用 如何在helper中使用此。$存储Javascript 如何访问Vuex store in helper函数?,javascript,vuejs2,vuex,Javascript,Vuejs2,Vuex,对于vue axios auth by api_令牌,我使用帮助文件api.js 我得到错误-UncaughtTypeError:无法读取未定义的属性“getters” 我认为api.js helper没有看到全局存储—Vuex$store 在其他组件中,我不需要导入Vuex存储,他可以在应用程序的任何位置使用 如何在helper中使用此。$存储 //api.js import axios from 'axios' let api_token = this.$store.getters.ge
//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);
})
}
}
找到答案
// some JS file
import store from './../store'; // path to your Vuex store
let user = store.getters.user;
// do stuff with user
问题是,从架构的角度来看,它是否正确。当我这样做时,我会得到一个代理对象