vue3 动态设置ref

静态ref的获取与使用
<template>
    <div ref="cptRef">...</div>
</template>
<script setup>
    import { ref } from 'vue'
    const cptRef = ref(null)
    // 可通过cptRef.value获取组件上的属性或方法
</script>
//动态ref
<template>
    <el-button :ref="setItemRef">动态Ref</el-button>
</template>
<script setup>
    import { ref } from 'vue'
    
    // 设置一个遍历用来保存动态的ref对象
    const tableRef = ref(null)
    // 赋值动态ref到变量
    const setItemRef = el => {
        if (el) {
            tableRef.value = el
        }
    }
</script>
//v-for设置ref及其使用
<template>
    <component v-for="item in cptArr" :key="item.type" :ref="setItemRef" :is="item.type"></component>
</template>
<script setup>
    import { ref } from 'vue'
    const cptArr = [
        {
            type: 'imgCpt',
            option: {}
        },
        {
            type: 'advCpt',
            option: {}
        }
    ]
    const itemRefs = []
    const setItemRef = el => {
        if (el) {
            itemRefs.push(el)
        }
    }
    itemRefs.forEach(item => {
        // item 即为对应的组件ref
        // 可通过 item 获取对应组件上的属性或方法
    })
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值