首页 > 解决方案 > 从 App.vue 发出事件并在组件中捕获

问题描述

我正在尝试在 Vue 中实现注销处理。我重定向到主页,它在所有页面上都可以正常工作,除了主页没有刷新。所以我决定在捕捉到它后发出一个信号并刷新数据。

应用程序.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' });
    }
  },

主页.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');
  },
},

但信号没有到达 Home.vue 或被忽略。我该如何解决?或者您对此退出程序有更好的解决方案吗?

标签: vue.js

解决方案


当你使用钩子时$emit

$root你应该从你的 vuejs 应用程序中监听这个事件, $root. 因此,为了达到预期的结果,您只需将代码更改为:

在您的组件home中(我只放置script.vue 文件中的会话)

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

带有操作注销的组件。

<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>

如果你想了解更多,这里是在 vuejs 中处理事件的文档。


推荐阅读