// 父组件 ParentComponent.vue
<template>
<div>
<ChildComponent ref="childComponent" />
<button @click="callChildMethod">调用子组件方法</button>
</div>
</template>
<script>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
setup() {
const childComponent = ref(null);
const callChildMethod = () => {
if (childComponent.value) {
childComponent.value.childMethod();
}
};
return {
childComponent,
callChildMethod
};
}
};
</script>
// 子组件 ChildComponent.vue
<template>
<div>
<!-- 子组件内容 -->
</div>
</template>
<script>
export default {
methods: {
childMethod() {
console.log('子组件的方法被调用了');
}
}
};
</script>
父组件 (ParentComponent.vue):
ref 来引用子组件实例 (ChildComponent)。setup 函数中定义了一个 callChildMethod 方法,该方法通过 childComponent.value.childMethod() 调用子组件的 childMethod 方法。callChildMethod 方法。子组件 (ChildComponent.vue):
childMethod 方法,在控制台输出一条消息,表示方法被调用。这样,父组件就可以通过 ref 引用来调用子组件的方法。
上一篇:vue3登录界面
下一篇:npm启动vue项目
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站