programing

How to use store in Vue/ Nuxt plugin?

goodcopy 2022. 7. 27. 22:16
반응형

How to use store in Vue/ Nuxt plugin?

I am writing a nuxt app that authenticates with a backend. I have a http plugin that intercepts all http requests. 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.

ReferenceURL : https://stackoverflow.com/questions/50233438/how-to-use-store-in-vue-nuxt-plugin

반응형