好的,以下是一个简单的案例:
父组件 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.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>
在这个案例中,子组件通过调用$emit
方法向父组件发送一个自定义事件text-updated
,并传递一个字符串参数来更新父组件中的childText
数据,从而实现子组件调用父组件的方法。在父组件中,我们监听了text-updated
事件,并将其对应的处理方法updateText
定义在父组件中,当子组件调用$emit
方法时,该方法会被自动触发,从而更新父组件中的数据。