Categories
Vue Answers

How to add Vue.js event on window?

Spread the love

Sometimes, we want to add Vue.js event on window.

In this article, we’ll look at how to add Vue.js event on window.

How to add Vue.js event on window?

To add Vue.js event on window, we can call window.addEventListener in our Vue component’s methods.

For instance, we write

<script>
//...
export default {
  //...
  methods: {
    keyDown() {
      const activeElement = this.$refs.el;
      if (activeElement && !isNaN(event.key) && event.key > 0) {
        activeElement.innerHTML = event.key;
      }
    },
  },

  created() {
    window.addEventListener("keydown", this.keyDown);
  },

  destroyed() {
    window.removeEventListener("keydown", this.keyDown);
  },
  //...
};
</script>

to call window.addEventListener with the 'keydown' event and the this.keyDown method as the event handler callback in the created hook.

And then we call window.removeEventListener with the same arguments to clear the listeners in the destroyed hook to remove the listeners when the component unmounts.

Conclusion

To add Vue.js event on window, we can call window.addEventListener in our Vue component’s methods.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *