// 父组件 ParentComponent.vue
<template>
<div>
<child-component @custom-event="parentMethod"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
parentMethod() {
console.log('Parent method called');
}
}
};
</script>
// 子组件 ChildComponent.vue
<template>
<div>
<button @click="callParentMethod">Call Parent Method</button>
</div>
</template>
<script>
export default {
methods: {
callParentMethod() {
this.$emit('custom-event');
}
}
};
</script>
父组件 (ParentComponent.vue):
<child-component>,并通过 @custom-event="parentMethod" 监听子组件发出的自定义事件。parentMethod,当子组件触发 custom-event 时,这个方法会被调用。子组件 (ChildComponent.vue):
callParentMethod 方法。callParentMethod 方法通过 this.$emit('custom-event') 触发一个自定义事件 custom-event,通知父组件调用其方法。通过这种方式,子组件可以通过事件机制调用父组件的方法。
上一篇:vue3 created方法
下一篇:vue3 emit用法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站