[英]How to use store in Vue/ Nuxt plugin?
I am writing a nuxt app that authenticates with a backend. 我正在编写一个通过后端进行身份验证的nuxt应用。 I have a http plugin that intercepts all http requests.
我有一个HTTP插件,可拦截所有HTTP请求。 I need to add an auth token to all requests, the token is in the store.
我需要向所有请求添加身份验证令牌,该令牌在商店中。 What I want to know is, how do I access the store from the plugin?
我想知道的是,如何从插件访问商店?
import axios from 'axios';
var api = axios.create({
baseURL: 'http://127.0.0.1:8000/api/'
});
api.interceptors.request.use(function (config) {
config.headers = {
'Authorization': 'Bearer' + **how do access store?**
}
return config;
}, function (error) {
return Promise.reject(error);
});
export default api;
Thanks 谢谢
You can try to use app store from context in plugin. 您可以尝试从插件的上下文中使用应用程序商店。 Your plugin need some changes:
您的插件需要一些更改:
import axios from 'axios';
var api = axios.create({
baseURL: 'http://127.0.0.1:8000/api/'
});
export default (context, inject) => {
api.interceptors.request.use(function (config) {
config.headers = {
'Authorization': 'Bearer' + context.app.$store.state.your_path_to_token
}
return config;
}, function (error) {
return Promise.reject(error);
});
return api;
}
One more way it's create store/index.js file and import them into plugin. 它是创建store / index.js文件并将其导入插件的另一种方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.