Custom Events
# Custom Events
# Events bound with v-on on component tags are custom events
<div id="root">
<child @click="handleClick"></child> <!--here click is a custom event-->
</div>
<script type="text/javascript">
Vue.component('child', {
template: '<button>Child</button>',
})
var vm = new Vue({
el: '#root'
methods: {
handleClick() {
alert('click')
}
}
})
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
In the code above, clicking the child component will NOT trigger the handleClick() event, because click here is not a native click event but a custom event.
To trigger the click event on the component tag, you need to emit it from the child component using $emit:
<div id="root">
<child @click="handleClick"></child>
</div>
<script type="text/javascript">
Vue.component('child', {
template: '<button @click="handleChildClick">Child</button>', // click here is a native event
methods: {
handleChildClick() {
this.$emit('click')
}
}
})
var vm = new Vue({
el: '#root'
methods: {
handleClick() {
alert('click')
}
}
})
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
In the code above, the click inside the child component is a native click event, which emits a click custom event via $emit to trigger the parent's handleClick().
# Turning a custom event into a native event
Use the .native modifier to turn a custom event into a native event:
<div id="root">
<child @click.native="handleClick"></child> <!--custom event with native modifier becomes a native event-->
</div>
<script type="text/javascript">
Vue.component('child', {
template: '<button>Child</button>',
})
var vm = new Vue({
el: '#root'
methods: {
handleClick() {
alert('click')
}
}
})
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
In the code above, the custom event click has the .native modifier added, making it a native event and thus triggering handleClick().
# Custom event names are automatically lowercased
When using camelCase for custom event names:
this.$emit('myEvent')
Listening for the kebab-case version of that name will have no effect:
<!-- no effect -->
<my-component v-on:my-event="doSomething"></my-component>
2
v-on event listeners inside DOM templates will be automatically converted to all lowercase (because HTML is case-insensitive), so v-on:myEvent will become v-on:myevent -- making it impossible to listen for myEvent.
Therefore, we recommend always using kebab-case for event names.