Home > Enterprise >  How to set listener on document in vue to get control on key press?
How to set listener on document in vue to get control on key press?

Time:04-23

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.

CodePudding user response:

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.com/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>

CodePudding user response:

Without knowing the scope of your Vue model/component, 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.

  • Related