[Vuejs]-Vue.js listen event only when top

0👍

If the wrapper of your component is a div, you can add tabindex attribute, so the div can receive keypress event

And then you can add keypress event to this.$el instead of global window

Vue.component('greeting', {
  template: '<div tabindex="1">Welcome to coligo!</div>',
  props: ['name'],
  mounted() {
    this.$el.addEventListener('keypress', (e) => {
      console.log(this.name, e)
    })
  },
  methods: {
  }
});

// create a new Vue instance and mount it to our div element above with the id of app
var vm = new Vue({
  el: '#app'
});

Demo https://jsfiddle.net/ittus/6b2ru73t/

Leave a comment