父组件
在父组件中调用子组件的sayHello()函数
javascript
<template>
<div>
<button @click="getChild('wendu')">触发子组件方法wendu</button>
<button @click="getChild('shidu')">触发子组件方法shidu</button>
<el-dialog v-model="dialogVisible" title="title" width="80%" draggable style="background: #091b37 !important; padding:1px !important" :close-on-click-modal="false">
<transition>
<keep-alive>
<component :is="Child" ref="childRef" :key="b"> </component>
</keep-alive>
</transition>
</el-dialog>
</div>
</template>
<script setup>
import { ref, nextTick } from 'vue'
import Child from './components/wendu.vue'
const b = ref('')
const dialogVisible = ref(false)
// 定义与 ref 同名变量
const childRef = ref(null)
const getChild = (a) => {
dialogVisible.value = true
b.value = a
nextTick(() => {
if (childRef.value) {
console.log(childRef.value);
console.log(childRef.value.sayHello);
childRef.value.sayHello(a);
} else {
console.log("子组件尚未渲染");
}
})
}
</script>
子组件
javascript
<template>
<div>我是子组件</div>
<input type="text" v-model="inputValue">
</template>
<script setup>
import { ref, defineExpose } from 'vue'
// 第一步:定义子组件的方法
const sayHello = (value) => {
console.log(value)
}
// 第二部:暴露方法
defineExpose({
sayHello
})
</script>