The .native Event Modifier In Vue.js

yossiabramov

Yossi Abramov

Posted on August 10, 2020

The .native Event Modifier In Vue.js

Easy event handling is one of the most prominent features of Vue.js. However, there are some event handling concepts that I wish someone would have shared with me from day one!

Maybe you have encountered this problem: you have a component, say <special-button /> and you want to include it in your App.vue (or any other .vue file for that matter) and bind a click event to it:

<template>
  <div>
    <special-button @click="onClick" />
  </div>
</template>

<script>
import SpecialButton from "./components/SpecialButton";
export default {
  components: {
    SpecialButton,
  },
  methods: {
    onClick() {
      console.log("Clicked");
    },
  },
};
</script>
Enter fullscreen mode Exit fullscreen mode

Now, you will find that this event does not fire when clicking your <special-button />. The reason this does not work is because @click is a native event that you are trying to bind to a Vue component. To fix this, all you have to do is simply add the .native event modifier to your event-listener:

<template>
  <div>
    <special-button @click.native="onClick" />
  </div>
</template>
Enter fullscreen mode Exit fullscreen mode

Read more about the .native modifier on the official Vue docs:

πŸ‘‰ https://vuejs.org/v2/guide/components-custom-events.html#Binding-Native-Events-to-Components

✍ This post was originally published on my blog, for more Vue.js and js posts: https://yossiabramov.com/

πŸ’– πŸ’ͺ πŸ™… 🚩
yossiabramov
Yossi Abramov

Posted on August 10, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related