I've three pages home, about & details
and I added a keydown
event listener on Vue mounted
lifecycle hook for each page, so whenever user clicks ctrl + rightArrow
I'm triggering nextPage()
method, which will push the next page to vue router, similarly ctrl + leftArrow
should trigger the prevPage()
. I'm implementing the same functionality on each page with different routes in nextPage() & prevPage()
. Here the problem is, even though I didn't add the keydown
listener on some of the pages, the event is triggering and navigating to the routes from the previously loaded event listener also the previous listeners are triggering multiple times.
export default {
mounted() {
window.addEventListener('keydown', this.handleKeyPress);
},
methods: {
handleKeyPress(e) {
if (e.ctrlKey && e.keyCode === 37) { // Previous page
this.prevPage();
} else if (e.ctrlKey && e.keyCode === 39) { // Next page
this.nextPage();
}
},
nextPage() {
this.$router.push({ name: 'about' });
},
prevPage() {
this.$router.push({ name: 'home' });
}
}
}