Ok, here's a simple case:
Parent component Parent.vue:
<template>
<div>
<h2>Parent Component</h2>
<child-component @text-updated="updateText"/>
<p>Text from child component: {
{ childText }}</p>
</div>
</template>
<script>
import ChildComponent from './Child.vue';
export default {
components: {
ChildComponent
},
data() {
return {
childText: ''
}
},
methods: {
updateText(text) {
this.childText = text;
}
}
}
</script>
Child component Child.vue:
<template>
<div>
<h2>Child Component</h2>
<button @click="updateParentText()">Update Parent Text</button>
</div>
</template>
<script>
export default {
methods: {
updateParentText() {
this.$emit('text-updated', 'Text updated from child component');
}
}
}
</script>
In this case, the child component$emit
sends a custom event to the parent component by calling the methodtext-updated
, and passes a string parameter to update the data in the parent componentchildText
, so that the child component calls the method of the parent component. In the parent component, we listened totext-updated
the event andupdateText
defined its corresponding processing method in the parent component. When the child component calls$emit
the method, the method will be automatically triggered to update the data in the parent component.