Vue JS 如何删除僵尸事件?

Vue JS How to remove zombie event?

如何移除丧尸事件?

当 $on 事件向前和向后切换多次时。

App.vue

<template>
  <input type="button" @click.prevent="click()" value="click">
<template>

<script>
  export default { 
    methods: {
      click: function (){
        this.$emit('go')
      }
    }
  }
<script>

Children.vue

<script>
  export default {
    methods: {
      go: function () {
        console.log('event received')
      }
    },
    created: function (){
        this.$parent.$on('go', this.go);
    }
  }
<script>

您在 created 生命周期钩子中有 click 方法,因此只要呈现 children 组件就会调用它。

移除组件时需要移除事件:

<script>
  export default {
    methods: {
      go: function () {
        console.log('event received')
      }
    },
    created: function (){
        this.$parent.$on('go', this.go);
    },
    beforeDestroy: function (){
        this.$parent.$off('go',this.go);
    }
  }
<script>