在setup()钩子函数中调用
父组件
<template>
<div>
我是父组件
<children ref="childrenRef" />
<button @click="handleChildren">触发子组件</button>
</div>
</template>
<script lang="ts">
import { ref, defineComponent } from 'vue'
import Children from './components/Children.vue';
export default defineComponent({
components: { Children }
setup() {
const childrenRef = ref<any>();
const handleChildren = () => childrenRef.value.isChildren();
return {
childrenRef,
handleChildren
}
},
})
</script>
子组件:
<template>
<div>
我是子组件
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
setup() {
const isChildren = () => {
console.log("我是子组件");
}
return {
isChildren,
}
}
})
</script>
如果是在setup() 钩子函数中使用,父组件通过ref 获取到子组件实例后,直接.value.函数名 即可调用子组件所定义的函数。其中ref的泛型可以指定any 和InstanceType<typeof Children>
在<srcipt setup>中调用
父组件
<template>
<div>
我是父组件
<children ref="childrenRef" />
<button @click="handleChildren1">触发子组件1</button>
<button @click="handleChildren2">触发子组件2</button>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import Children from './components/Children.vue';
const childrenRef = ref<InstanceType<typeof Children>>();
const handleChildren1 = () => childrenRef.value?.isChildren();
const handleChildren2 = () => childrenRef.value?.isChildren2();
</script>
子组件
<template>
<div>
我是子组件
</div>
</template>
<script setup lang="ts">
import { defineExpose } from 'vue';
const isChildren = () => {
console.log("我是子组件的第一个方法");
}
const isChildren2 = () => {
console.log("我是子组件的第二个方法");
}
defineExpose({ isChildren, isChildren2 })
</script>
在<srcipt setup> 中调用和setup() 钩子函数中调用不同的是:子组件中要通过defineExpose 将方法暴露给父组件。
📃官网说明地址
|