简体   繁体   中英

Is it possible to access vue instance in axios interceptors?

I'm using vue-reactive-storage since localStorage is not reactive. Usage of this plugin creates a vue object accessible to all components. I want to access this object within my axios interceptors response function but I get the common TypeError: Cannot read property 'localStorage' of undefined .

app.js:

require('./bootstrap');

import Vue from 'vue';
import Vuetify from 'vuetify';
import reactiveStorage from "vue-reactive-storage";
import store from './store/index';

Vue.use(Vuetify);
Vue.use(reactiveStorage, {
  "snackBar": {show: false, text: '(Initial snackbar text.)', type: 'info', timedelay: 2000},
});

axios.interceptors.response.use(response => response, error => {
    this.localStorage.snackBar.text = error.response.data.message || 'Request error status: ' + error.response.status,
    this.localStorage.snackBar.type = 'error'
    this.localStorage.snackBar.show = 'true'
})

import router from './routes';

const app = new Vue({
    el: '#app',
    vuetify: new Vuetify(),
    router,
    store,
    }
});

Is this possible?

Laravel v6.4.1, Vue v2.6.10

Why don't you use Vuex store? it is reactive. And you could add a plugin for your interceptor like this:

export default function ({ $axios, store, redirect, context }) {
    $axios.onResponse(response => {
    // your code
    store.commit('set_sample_data', response.data)
})
}

This is possible and is explained here .

TL;DR: Use an old fashioned function definition and set it to the prototype, to let this function gain your Vue instance's context binding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM