【问题标题】:Vue JS How to remove zombie event?Vue JS 如何移除僵尸事件?
【发布时间】:2017-01-18 17:49:53
【问题描述】:

如何移除僵尸事件?

当向前和向后切换时,$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>

【问题讨论】:

    标签: javascript vue.js vuejs2


    【解决方案1】:

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

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

    【讨论】:

    • 是的,这就是我需要的。谢谢。
    【解决方案2】:

    您在 created 生命周期钩子中有 click 方法,因此每当渲染 children 组件时都会调用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-18
      相关资源
      最近更新 更多