Garry
Garry

Reputation: 33

Vue js call method of global component from main.js

Goal here is to show the LOGIN modal when the API returns status 401

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

Upvotes: 0

Views: 620

Answers (1)

Thomas Bay
Thomas Bay

Reputation: 649

One way to accomplish what you are asking for, you can emit on your $root/vm, even though it in many cases is best practice to avoid doing so.

Anyway, in your main.js you can add this:

axios.interceptors.response.use(
  res => res,
  err => {
    if (err.response.status == 401) {
      vm.$emit('openLogin');
    }
  }
);

Then add your login modal to your App.vue instead of main.js, and in there listen on $root in mounted like so:

mounted() {
  this.$root.$on('openLogin', () => {
    this.$refs.loginModal.open()
  })
}

Upvotes: 2

Related Questions