Goal here is to show the LOGIN modal when the API returns status 401
For complete discussion check this link
Question
We have added a component in main.js
var vm = new Vue({
el: '#app',
router,
store
});
Vue.component('login-modal',
() => import('./components/LoginModal')
)
In main.js using axios.interceptors.response.use() to check the status of all ajax requests. Works fine but now need to call the function of LoginModal which will open the modal in case status of API is 401
axios.interceptors.response.use(
res => res,
err => {
if (err.response.status == 401) {
router.push('/login')
//call to component method instead instead of **router.push('/login')**
}
}
);
In vue templates we use references like this
this.$refs.loginModal.open()
but don’t know how we can call component function from main.js
Answer: The solution is to emit the event from main.js then listen it in the component
In main.js
axios.interceptors.response.use( res => res, err => { if (err.response.status == 401) { vm.$emit('openLogin'); } } );
and in the component
mounted() { this.$root.$on('openLogin', () => { this.$refs.loginModal.open() }) }
For complete discussion check this link