我正在使用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
答案 0 :(得分:0)
您为什么不使用Vuex商店?它是反应性的。您可以像这样为拦截器添加一个插件:
export default function ({ $axios, store, redirect, context }) {
$axios.onResponse(response => {
// your code
store.commit('set_sample_data', response.data)
})
}
答案 1 :(得分:0)
这是可能的,并在here中进行了解释。
TL; DR:使用老式的函数定义并将其设置为原型,以使该函数获得Vue实例的上下文绑定。