【问题标题】:Is it possible to access vue instance in axios interceptors?是否可以在 axios 拦截器中访问 vue 实例?
【发布时间】:2020-03-08 05:06:46
【问题描述】:

我正在使用 vue-reactive-storage 因为 localStorage 不是响应式的。使用这个插件会创建一个可供所有组件访问的 vue 对象。我想在我的 axios 拦截器响应函数中访问这个对象,但我得到了常见的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,
    }
});

这可能吗?

Laravel v6.4.1、Vue v2.6.10

【问题讨论】:

    标签: javascript vue.js axios


    【解决方案1】:

    你为什么不使用 Vuex 商店?它是反应性的。你可以像这样为你的拦截器添加一个插件:

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

    【讨论】:

    • 感谢您的建议,但它没有回答我的问题。
    【解决方案2】:

    这是可能的,并在here进行了解释。

    TL;DR:使用老式函数定义并将其设置为原型,让此函数获得您的 Vue 实例的上下文绑定。

    【讨论】:

      最近更新 更多