ref
靜態(tài)ref的獲取與使用
<template>
<div ref="cptRef">...</div>
</template>
<script setup>
import { ref } from 'vue'
const cptRef = ref(null)
// 可通過(guò)cptRef.value獲取組件上的屬性或方法
</script>
動(dòng)態(tài)ref
:ref="varRef" 設(shè)置ref及其使用
<template>
<el-button :ref="setItemRef">動(dòng)態(tài)Ref</el-button>
</template>
<script setup>
import { ref } from 'vue'
// 設(shè)置一個(gè)遍歷用來(lái)保存動(dòng)態(tài)的ref對(duì)象
const tableRef = ref(null)
// 賦值動(dòng)態(tài)ref到變量
const setItemRef = el => {
if (el) {
tableRef.value = el
}
}
</script>
遍歷ref
v-for設(shè)置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 即為對(duì)應(yīng)的組件ref
// 可通過(guò) item 獲取對(duì)應(yīng)組件上的屬性或方法
})
</script>