loading...

The .native Event Modifier In Vue.js

yossiabramov profile image Yossi Abramov Originally published at yossiabramov.com ・1 min read

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>

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>

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/

Posted on by:

yossiabramov profile

Yossi Abramov

@yossiabramov

I'm a full stack web developer. I write about JS, Vue.js, PHP, Laravel, Wordpress and more web stuff.

Discussion

markdown guide