静态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>
Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐