如何优化在vue组件中使用addEventListener 和 removeEventListener

1
2
3
4
5
6
7
8
9
10
11
12
13
export default {
created () {
document.addEventListener('keydown', this.handleKeydown)
},
destroyed () {
document.removeEventListener('keydown', this.handleKeydown)
},
methods: {
handleKeydown (e) {
console.log(e.key)
}
}
}

去掉在methods里面定义方法

1
2
3
4
5
6
7
8
9
10
11
export default {
created () {
this.handleKeydown = (e) => {
console.log(e.key)
}
document.addEventListener('keydown', this.handleKeydown)
},
destroyed () {
document.removeEventListener('keydown', this.handleKeydown)
}
}

去掉挂载到当前实例

1
2
3
4
5
6
7
8
9
10
11
12
export default {
created () {
const handle = (e) => {
console.log(e.key)
}
document.addEventListener('keydown', handle)
this.$once('hook:destroyed', () => {
document.removeEventListener('keydown', handle)
})
}
}