我正在使用 vue-reactive-storage 因为 localStorage 不是 react 性的。使用此插件会创建一个可供所有组件访问的 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
最佳答案
为什么不使用 Vuex 商店?它是 react 性的。您可以为您的拦截器添加一个插件,如下所示:
export default function ({ $axios, store, redirect, context }) {
$axios.onResponse(response => {
// your code
store.commit('set_sample_data', response.data)
})
}
关于javascript - 是否可以在 axios 拦截器中访问 vue 实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58819529/