vue3项目实战之在线客服-⑥ 父组件调用子组件方法

子组件

<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>

大公告成! 这样父组件就可以调用子组件的方法和函数了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值