[英]How to remove event listener from Vue Component
我有一個 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>
您可以將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>
您必須保留對已注冊點擊處理程序的引用,以便以后能夠將其刪除:
mounted() {
this.clickHandler = () => { ... };
window.addEventListener('click', this.clickHandler);
}
beforeDestroy() {
window.removeEventListener('click', this.clickHandler);
}
但是,您似乎已經在組件中定義了這個 function 。 它被命名為handleClickEvent
。 所以沒有理由在它周圍創建一個箭頭 function 包裝器。 你可以直接使用它:
mounted() {
window.addEventListener('click', this.handleClickEvent);
}
beforeDestroy() {
window.removeEventListener('click', this.handleClickEvent);
}
vue2 中可用的另一個巧妙功能(遺憾的是,vue3 中沒有)是動態注冊一個鈎子,它允許在mounted()
中添加和刪除處理程序,而無需在組件中保留對它的引用:
mounted() {
const handler = () => { ... }; // local variable
window.addEventListener('click', handler);
this.$once('hook:beforeDestroy',
() => window.removeEventListener('click', handler)
);
}
https://v2.vuejs.org/v2/guide/components-edge-cases.html#Programmatic-Event-Listeners
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.