vue3 script setup 父组件调用子组件方法
vue3 script setup 父组件调用子组件方法
·
父组件
<template>
<div class="parent">
<button @click="getChild">触发子组件方法</button>
<!-- 1. 定义ref -->
<child ref="childRef"></child>
</div>
</template>
<script lang="ts" stup>
import { defineComponent, ref } from "vue";
import child from "@/components/child.vue";
// 2. 定义与ref同名变量
const childRef = ref<any>();
const getChild = () => {
childRef.value.childFun();
}
</script>
子组件 scrip setup 写法
<template>
<div class="child">
</div>
</template>
<script lang="ts" stup>
const childFun = () => {
console.log('已触发组件方法');
}
//关键点 把 方法暴露给父组件
defineExpose({open})
</script>
子组件 defineComponent 写法
<template>
<div class="child">
</div>
</template>
<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
setup() {
// 子组件的方法
const childFun = () => {
console.log('已触发组件方法');
}
return {
childFun
};
},
});
</script>
更多推荐
已为社区贡献2条内容
所有评论(0)