Leos Literak
Leos Literak

Reputation: 9474

Emit event from App.vue and catch in component

I am trying to implement sign out handling in Vue. I redirect to Home which works fine on all pages except Home which is not refreshed. So I decided to emit a signal and refresh data once I catch it.

App.vue

<b-dropdown-item href="#0" v-on:click="signMeOut()">Sign out</b-dropdown-item>

methods: {
  signMeOut() {
    this.$store.dispatch('SIGN_USER_OUT');
    if (this.$route.path === '/') {
      this.$emit('sign-out');
    } else {
      this.$router.push({ name: 'home' });
    }
  },

Home.vue

<b-container fluid="true" class="pt-3 w-75 m-auto" v-on:sign-out="reload">

created() {
  this.$store.dispatch('INIT_STREAM');
},
methods: {
  reload() {
    console.log('reload');
    this.$store.dispatch('INIT_STREAM');
  },
},

but the signal does not reaches the Home.vue or is ignored. How can I fix it? Or do you have a better solution of this sign out procedure?

Upvotes: 3

Views: 2851

Answers (1)

Danizavtz
Danizavtz

Reputation: 3270

When you use the hook $emit.

You should listen to this event in $root instance from your vuejs application, $root. So for achieve the desired result you just have to change your code to:

In your component home (I'm putting only the session script from a .vue file)

<script>
export default {
  name: 'Home',
  components: {
    HelloWorld
  },
  created(){
    this.$root.$once('mylogouthandler', this.logoutEventHandler)
  },
  methods: {
    logoutEventHandler() {
      console.log('exit')
      //do your stuff here.
    }
  }
}
</script>

your component with action logout.

<template>
  <div class="about">
    <button @click="handleButtonClick()">logout</button>
    
  </div>
</template>
<script>
export default {
  name: 'About',
  methods: {
    handleButtonClick(){
      console.log('clicked')
      this.$root.$emit('mylogouthandler')
    }
  }
}
</script>

If you would like to know more, here is the documentation for handling events in vuejs.

Upvotes: 2

Related Questions