vue3 div 绑定 ref 正常是这样的:
<script setup>
import {ref} from "vue";
const divRef1 = ref(null)
const divRef2 = ref(null)
const divRef3 = ref(null)
</script>
<template>
<div ref="divRef1"></div>
<div ref="divRef2"></div>
<div ref="divRef3"></div>
</template>
<style scoped>
</style>
这样的怎么不可以:
<script setup>
import {ref} from "vue";
const divRefs = ref({
divRef1: null,
divRef2: null,
divRef3: null,
})
</script>
<template>
<div ref="divRefs.divRef1"></div>
<div ref="divRefs.divRef2"></div>
<div ref="divRefs.divRef3"></div>
</template>
<style scoped>
</style>
vue
解析ref="xxx"
属性时检查你的script
中有没有同名的xxx
的ref
,有就绑定,换句话说是检查你的setupState
上有没有同名的xxx
属性;所谓
setupState
就是你setup() { return state }
这里的return
的值,<script setup>
是简写的语法糖,如果换成这样写就有值了:如果你有多个

ref
想集中在一个对象上访问,不想定义太多ref
变量,你可以通过实例去访问:getCurrentInstance().refs.xxx
或者改成函数形式:
