如何从 Vue 组件中删除事件监听器
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>
我有一个 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>