
我爱模板网层分享一篇关于vue3使用ref的文章:vue2 $refs在vue3中的使用方法,但那个是静态的ref,使用方法如下:
静态ref的获取与使用:
<template>
<div ref="cptRef">...</div>
</template>
<script setup>
import { ref } from 'vue'
const cptRef = ref(null)
// 可通过cptRef.value获取组件上的属性或方法
</script>如果ref是动态的,就不能这么使用了,而是预先定义,然后动态赋值:
//动态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>