vue3: ref、动态ref

ref

静态ref的获取与使用

<template>
    <div ref="cptRef">...</div>
</template>
<script setup>
    import { ref } from 'vue'
    const cptRef = ref(null)
    // 可通过cptRef.value获取组件上的属性或方法
</script>

动态ref

:ref="varRef" 设置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>

遍历ref

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>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容