【问题标题】:How to remove event listener from Vue Component如何从 Vue 组件中移除事件监听器
【发布时间】:2022-01-15 23:56:46
【问题描述】:

我有一个 Vue2 组件,其中包含我在 mounted 创建的添加的 eventListener。我想知道当组件被销毁时如何正确删除这个监听器?

<template>
    <div>
      ...
    </div>
  </template>
  
  <script>
  export default {
    mounted() {
        window.addEventListener('click', (evt) => {
          this.handleClickEvent(evt)
        })
    },
    destroyed() {
      //   window.removeEventListener('click', ????);
    },
    methods: {
      handleClickEvent(evt) {
        // do stuff with (evt) 
      },
    },
  }
  </script>
  

【问题讨论】:

    标签: javascript vue.js vuejs2 components


    【解决方案1】:

    您可以将this.$el 用于整个组件并像您创建它一样销毁事件:

    Vue.component('Child', {
      template: `
        <div class="child">
          click for event
        </div>
      `,
      mounted() {
        this.$el.addEventListener('click', (evt) => {
          this.handleClickEvent(evt)
        })
      },
      beforeDestroy() {
        console.log('distroyed')
        this.$el.removeEventListener('click', (evt) => {
          this.handleClickEvent(evt)
        })
      },
      methods: {
        handleClickEvent(evt) {
          console.log(evt.currentTarget)
          // do stuff with (evt) 
        },
      },
    })
    
    
    new Vue({
      el: "#demo",
      data() {
        return {
          show: true
        }
      },
      methods: {
        toggleShow() {
          this.show = !this.show
        }
      }
    })
    .child {
      height: 150px;
      width: 200px;
      background: goldenrod;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="demo">
      <div>
        <button @click="toggleShow">mount/unmount component</button>
        <Child v-if="show" />
      </div>
    </div>

    【讨论】:

      猜你喜欢
      • 2015-09-17
      • 1970-01-01
      • 2018-05-15
      • 2019-04-11
      • 2021-12-27
      • 2011-12-30
      • 1970-01-01
      • 2012-02-09
      • 2021-08-23
      相关资源
      最近更新 更多