最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to set listener on document in vue to get control on key press? - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 4

Without 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>

发布评论

评论列表(0)

  1. 暂无评论