Reputation: 139
I am in the process of building my first Vue.js project, and I would like to navigate between pages (prev page/next page) through the left and right keyboard arrow keys.
I've created a simple alert test (and attached my code at the bottom of my ask) to demonstrate the problem I'm facing. When using v-on:click
, the alert method I created works perfectly fine. I've tried using v-on:keyup
, v-on:keydown
, and v-on:keypress
and neither option triggered an alert to indicate the arrowkey functionality was working.
I discovered this 3+ year old thread detailing a similar problem, and one of the comments described the method I'm using as being a working solution since v1.0.0. I've checked the key modifier documentation of the current version of Vue and it seems as though I am doing everything correctly.
I'm most likely missing something crucial, but after much experimentation and research, I could use some help. Thanks in advance!
new Vue({
el: "#app",
methods: {
popupLeft: function(){
alert("You have gone to the previous page");
},
popupRight: function(){
alert("You have gone to the next page");
},
popupClose: function(){
alert("You have closed this page");
},
}
})
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<div id="app">
<button @keyup.left="popupLeft">Prev Page</button>
<button @keyup.right="popupRight">Next Page</button>
<button @click="popupClose">Close Page</button>
</div>
Upvotes: 6
Views: 9663
Reputation: 4732
Your code works just as expected.
If you go to JSFiddle of example above and click the button at first and then use arrows - it will call corresponding events.
The reason is that you've added @keyup
listeners to buttons, meaning, only if button
element is in focus and @keyup
event fires - it will be handled.
In order to use arrow navigation, keyup
(or keydown
for my preference) event should be handled from window
or document
.
To do that, native event listener should be added with component's handlers:
Upvotes: 8