<template>
<div>
<!-- 父组件 -->
<parent-component>
<child-component @custom-event="handleEvent"></child-component>
</parent-component>
</div>
</template>
<script>
import ParentComponent from './ParentComponent.vue';
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ParentComponent,
ChildComponent
},
methods: {
handleEvent(data) {
console.log('父组件的方法被调用了', data);
}
}
};
</script>
<!-- ChildComponent.vue -->
<template>
<button @click="callParentMethod">点击调用父组件方法</button>
</template>
<script>
export default {
methods: {
callParentMethod() {
this.$emit('custom-event', '子组件传递的数据');
}
}
};
</script>
v-on
指令监听子组件发出的自定义事件 (@custom-event
),并将父组件的方法 (handleEvent
) 绑定到该事件上。$emit
方法触发自定义事件 (custom-event
),并将数据传递给父组件。当用户点击按钮时,子组件会调用 callParentMethod
方法,进而触发父组件的 handleEvent
方法。这种方式是 Vue.js 中常用的父子组件通信方式之一。
上一篇:使用vite创建vue3项目
下一篇:vue字符串转json对象
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站