v-for 中的 Ref 数组 — 非兼容
最后更新于:2022-04-02 08:13:42
>[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绑定的值的数据归并在一个数组中
~~~
~~~
~~~
* 如图

>[danger] ##### 看一个附加小问题
~~~
1.修改一下上面的案例将内外层的ref 命名都改成一样的'inItem',由于这友好将统一名字的ref归并在一个数组
的机制导致内外循环绑定的ref都在了一起
~~~
~~~
~~~
* 如图

>[info] ## vue3.x 使用
~~~
1.vue3并不会自动帮我们生成refs数组,只能得到最后一个元素的ref,想v-for 和 ref搭配需要手动去
创建变量来接受,ref 绑定一个方法
2.这个用来接收的变量不一定非要是数组
~~~
~~~
~~~
* 图一

* 图二看'itemRefs'

>[danger] ##### 注意
~~~
1.itemRefs 上面定义的是数组,也可以是对象
itemRefs: {}
setItemRef(el) {
let index = parseInt(Math.random(1) * 1000);
this.itemRefs[index] = el;
},
~~~
';