>[success] # v-for 中的 Ref 数组 ~~~ 1.在 Vue 2 中,在 v-for 里使用的 ref attribute 会用 ref 数组填充相应的 $refs property。 当存在嵌套的 v-for 时,这种行为会变得不明确且效率低下。 2.在 Vue 3 中,这样的用法将不再在 $ref 中自动创建数组。要从单个绑定获取多个 ref,请将 ref 绑定到 一个更灵活的函数上 (这是一个新特性) ~~~ >[info] ## vue2.x ~~~ 1.通过案例理解官网说的第一条'vue2.x' 帮我们把 'v-for' 绑定$refs将会自动生成一个refs的数组,自动将 一样的ref绑定的值的数据归并在一个数组中 ~~~ ~~~ <template> <div> <div v-for="(outter, outterIndex) in 5" :key="outterIndex" ref="OutTest"> <div v-for="(inner, innerIndex) in 5" :key="innerIndex" ref="inItem"> <!-- {{ item }} --> </div> </div> </div> </template> <script> export default { name: 'Test', mounted() { console.log(this.$refs) console.log(this.$refs.test) } } </script> ~~~ * 如图 ![](https://img.kancloud.cn/df/b3/dfb352a874c59e0e587368c576b295df_970x76.png) >[danger] ##### 看一个附加小问题 ~~~ 1.修改一下上面的案例将内外层的ref 命名都改成一样的'inItem',由于这友好将统一名字的ref归并在一个数组 的机制导致内外循环绑定的ref都在了一起 ~~~ ~~~ <template> <div> <div v-for="(outter, outterIndex) in 5" :key="outterIndex" ref="inItem"> <div v-for="(inner, innerIndex) in 5" :key="innerIndex" ref="inItem"> <!-- {{ item }} --> </div> </div> </div> </template> <script> export default { name: 'Test', mounted() { console.log(this.$refs) console.log(this.$refs.test) } } </script> <style></style> ~~~ * 如图 ![](https://img.kancloud.cn/99/88/9988bafc20210463d3eb0e8466fef99a_1104x147.png) >[info] ## vue3.x 使用 ~~~ 1.vue3并不会自动帮我们生成refs数组,只能得到最后一个元素的ref,想v-for 和 ref搭配需要手动去 创建变量来接受,ref 绑定一个方法 2.这个用来接收的变量不一定非要是数组 ~~~ ~~~ <template> <div> <p v-for="(item, index) in 5" :key="index+100" :ref="setItemRef">{{item}}</p> <p v-for="(item, index) in 5" :key="index" ref="test">{{item}}</p> <a ref="a1">1</a> <a ref="a2" @click="print">2</a> </div> </template> <script> export default { name: 'Test', mounted() { console.log(this.$refs) console.log(this.$refs.test) // 按照vue2的写法取出来是v-for渲染的最后一个dom元素 }, data() { return { itemRefs: [] } }, methods: { print() { console.log(this.itemRefs) }, setItemRef(el) { this.itemRefs.push(el) }, } // beforeUpdate() { // this.itemRefs = [] // }, // updated() { // console.log(this.itemRefs, 11111) // } } </script> <style></style> ~~~ * 图一 ![](https://img.kancloud.cn/03/2c/032c7488825e9dd0208842bbd57bce2b_389x65.png) * 图二看'itemRefs' ![](https://img.kancloud.cn/40/87/4087f21e7235d252bfdfa4b4c9fe3515_305x63.png) >[danger] ##### 注意 ~~~ 1.itemRefs 上面定义的是数组,也可以是对象 itemRefs: {} setItemRef(el) { let index = parseInt(Math.random(1) * 1000); this.itemRefs[index] = el; }, ~~~