Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
66
rated 0 times [  70] [ 4]  / answers: 1 / hits: 5301  / 6 Years ago, thu, october 25, 2018, 12:00:00

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:keypressand 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>




More From » vue.js

 Answers
6

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:



JSFiddle


[#10631] Wednesday, October 24, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kenyamelinad

Total Points: 339
Total Questions: 85
Total Answers: 116

Location: Marshall Islands
Member since Sun, Aug 29, 2021
3 Years ago
;