I've seen many websites where the search bar or similar can be focused by pressing Slash (Shift 7). One example would be the MDN Web Docs. I want to implement this for my Vue application. The Vue documentation mentions key modifiers for the most commonly used keys, like .enter
or .tab
, but there is no modifier for Slash. Also, since the user should be able to trigger the event anywhere on the page, the event listener cannot be applied to the input element itself. However, I don't know how to apply it to the whole website, since Vue applications are typically injected into a div
or similar element inside the body.
CodePudding user response:
For edge cased like these, it's okay to use regular javascript event listeners.
You can use Vue lifecycle methods to add and remove listeners. Here's a working example:
Vue.createApp({
mounted() {
window.addEventListener("keypress", this.onKeyPress);
},
beforeDestroy() {
window.removeEventListener("keypress", this.onKeyPress);
},
methods: {
onKeyPress(event) {
if (event.key !== "/") {
return;
}
if (document.activeElement === this.$refs.searchInput) {
return;
}
event.preventDefault();
this.$refs.searchInput.focus();
}
}
}).mount('#app')
input {
padding: 0.75em 2em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.2.31/vue.global.min.js" integrity="sha512-C/bodwN49fOc1z jln 2l9FlJ lZ8HifB30oLE87zMQwsfoWv6Ed25b/x646tlcKb7515VJrJK8uo1oIH1UR2Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<div id="app">
<input type="search" ref="searchInput" placeholder="Press / to search" />
</div>
Another solution could be a library like v-hotkey that adds a custom directive.
CodePudding user response:
<script src="https://unpkg.com/vue@3"></script>
<div id="app">
<input ref="input" />
</div>
<script>
Vue.createApp({
data() {
return {
show: true
}
},
mounted() {
window.addEventListener('keydown', (e) => {
if (e.key === '/' && this.$refs.input) {
e.preventDefault()
this.$refs.input.focus()
}
});
}
}).mount('#app')
</script>