在我的 Vue.js SPA 中,我有一个页面想要实现键盘交互。我使用 Vue Router 来方便链接。
到目前为止我已经注册
const interactiveComponent = {
//
methods: {
handleKeyboard(event) {
// do something
}
},
created() {
document.addEventListener('keydown', this.handleKeyboard);
},
//
};
问题是当我离开该页面时,处理程序仍然处于事件状态。
更糟糕的问题是,当我访问该页面,然后离开并返回时,处理程序会再次注册,并且我的事件会运行两次。
Vue.js 中是否存在任何约定来容纳这种处理程序?
最佳答案
您需要在 beforeDestroy
或 destroyed
Hook 中删除该事件监听器..
const interactiveComponent = {
//
methods: {
handleKeyboard(event) {
// do something
}
},
created() {
document.addEventListener('keydown', this.handleKeyboard);
},
beforeDestroy() {
document.removeEventListener('keydown', this.handleKeyboard);
},
};
关于javascript - 仅在一个 Vue Router 页面上处理 keydown 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58044847/