admin管理员组文章数量:1357225
Hello I'm looking for a way to create listener in vue like this:
document.addEventListener('keydown', function(event){
if(event.key === "Escape"){
console.log('hello esc ');
}
});
I need to change value of "varr" in
data(){
return{
varr: value
}
}
any time when user press esc btn. But it might be used in other casses. Please help.
Hello I'm looking for a way to create listener in vue like this:
document.addEventListener('keydown', function(event){
if(event.key === "Escape"){
console.log('hello esc ');
}
});
I need to change value of "varr" in
data(){
return{
varr: value
}
}
any time when user press esc btn. But it might be used in other casses. Please help.
Share Improve this question edited Apr 22, 2022 at 13:36 Nikola Pavicevic 23.5k9 gold badges29 silver badges51 bronze badges asked Apr 22, 2022 at 12:34 Jane JacekJane Jacek 2231 gold badge4 silver badges9 bronze badges2 Answers
Reset to default 4Without knowing the scope of your Vue model/ponent, the easiest suggestion would be to use the .mounted()
on your top-level Vue model…
Vue 2/Vue 3 Options API
// index.js
// in this example, the event handler is a Vue method
const vueModel = new Vue( {
…
methods:{
…
onKeydown( event ) {
if(event.key === "Escape"){
console.log('hello esc ');
this.varr = "new value";
}
},
…
},
mounted() {
document.addEventListener( "keydown", this.onKeydown );
},
…
} );
NOTE: This would be different if you're using Vue 3's Composition API. In that case, you'd want to set up your listener in either the setup()
or onMounted()
hook — depending on what your event handler affects and|or where you define the handler method.
You can use listener with modifier @keyup.esc
:
const app = Vue.createApp({
data() {
return {
varr: false
}
},
methods: {
handleEsc() {
console.log('hello esc ')
this.varr = !this.varr
}
},
mounted() {
this.$refs.div.focus()
}
})
app.mount('#demo')
<script src="https://unpkg./vue@3/dist/vue.global.prod.js"></script>
<div id="demo" >
<div @keyup.esc="handleEsc" tabindex="0" ref="div">
<p>press esc</p>
<p>varr: {{ varr }}</p>
</div>
</div>
本文标签: javascriptHow to set listener on document in vue to get control on key pressStack Overflow
版权声明:本文标题:javascript - How to set listener on document in vue to get control on key press? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743964701a2569669.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论