Vue – Component – $emit
$emit
Event trigger method.
We can use this trigger event by code.
Simple Example
vm.$on('test', function (msg) {
console.log(msg)
})
vm.$emit('test', 'hi')
Communicate with parent method
Use on and parent method, child can trigger parent method.
This is example from Vue documentation.
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>
<div id="fruits-counter">
<div v-for="fruit in fruits">
{{fruit.name}}: <counter-button v-on:increment="increment()"></counter-button>
</div>
<p>Total: {{total}}</p>
</div>
<script>
var counterButton = Vue.extend({
template: '<span>{{counter}} <button v-on:click="addToCart">Add</button></span>',
data: function () {
return {
counter: 0
}
},
methods: {
addToCart: function () {
this.counter += 1
this.$emit('increment')
}
},
});
new Vue({
el: '#fruits-counter',
components: {
'counter-button': counterButton
},
data: {
total: 0,
fruits: [
{name: 'Apple'},
{name: 'Grape'}
]
},
methods: {
increment: function () {
this.total += 1
}
}
});
</script>
</body>
</html>
