子组件
<script setup>
const show = () => {
alert('我是子组件,我11111的show方法被调用了')
};
let msg = '我是子组件的msg'
// 使用defineExpose把子组件方法变量导出供父组件使用
defineExpose({show, msg });
</script>
父组件 使用对象保存
<template>
<child :ref="(el)=>setItemRef(el, 'games'+item.gameId)" v-for="(item, index) in games" :key="index"/>
<button @click="btnClick">父组件调用子组件方法变量</button>
</template>
<script setup>
import { nextTick } from 'vue'
// 声明一个保存ref的对象
const gameRefs = {};
const setItemRef = (el, key) => {
if (el) {
gameRefs[key] = el;
}
};
const btnClick = async ()=>{
// 动态渲染组件需要使用nextTick等待更新
await nextTick()
let id = 3
const games3 = gameRefs['games'+id]
games3.show()
console.log(games3.msg)
}
</script>
方法二: 使用数组保存
<template>
<child :ref="setRef" v-for="(item, index) in games" :key="index"/>
<button @click="btnClick">父组件调用子组件方法变量</button>
</template>
<script setup>
import { nextTick } from 'vue'
// 声明一个保存ref的对象
const myRef = ref([]);
const setRef = (el) => {
myRef.value.push(el);
};
const btnClick = async ()=>{
// 动态渲染组件需要使用nextTick等待更新
await nextTick()
let id = 3
const games3 = myRef.value[0];
games3.show();
}
</script>
大公告成! 这样父组件就可以调用子组件的方法和函数了