<template> <div class="rain"> <div v-for="(item, index) in 8" :key="index" :ref="el => rain[index] = el" :data-set=" 'data' + index" /> <div ref='single'></div> </div></template><script>import { defineComponent, onMounted,onBeforeUpdate,onUpdated, ref } from 'vue'export default defineComponent({ setup() { const rain = ref([]) const single = ref() onMounted(() => { console.log('single', single.value) console.log('循环操dom', rain.value) console.log('循环操dom第一个', rain.value[0]) }) onBeforeUpdate(() => { }) onUpdated(() => { }) return { rain, single } },})</script>
输出结果
注意:最佳实践 vue3****使用v-for 循环时, 使用ref总会获取到的是最后的元素, 必须使用函数, 手动赋值, 不能用push, 会在更新的时候造成bug, 元素会重复
======>
vue2操作dom
<template> <div class="rain"> vue2 使用ref操作dom <div v-for="(item, index) in 8" :key="index" :ref="`rain-${index}`" :data-set=" 'data' + index" > inner{{ index }} </div> <div ref="single" /> </div></template><script>export default { mounted () { console.log('single', this.$refs.single) console.log('循环操dom', this.$refs['rain-0'][0]) }}</script>
vue2中的循环将统一名字的ref, 归并在一个数组的机制导致内外循环绑定的ref都在了一起,变得不明确
<template> <div class="rain"> vue2 使用ref操作dom <div v-for="(item, index) in 5" :key="index" ref="rains" :data-set=" 'data' + index" > out{{ index }} <div v-for="(item , index1) in 5" :key="index1" ref="rains" :data-set=" 'data-rains' + index" > inner{{ index1 }} </div> </div> <div ref="single" /> </div></template><script>export default { mounted () { console.log('single', this.$refs.single) console.log('循环操dom-rains', this.$refs.rains) }}</script>
输出结果:
vue3并不会自动帮我们生成refs数组,只能得到最后一个元素的ref,想v-for 和 ref搭配需要手动去 创建变量来接受,ref 绑定一个方法
<template> <div class="rain"> <div v-for="(item, index) in 8" :key="index" :ref="el => rain[index] = el" :data-set=" 'data-out' + index" > <div v-for="(item, index) in 8" :key="index" :ref="el => rain[index] = el" :data-set=" 'data-in' + index" > inner{{index1}} </div> </div> <div ref='single'></div> </div></template><script>import { defineComponent, onMounted,onBeforeUpdate,onUpdated, ref } from 'vue'export default defineComponent({ setup() { const rain = ref([]) const single = ref() onMounted(() => { console.log('single', single.value) console.log('循环操dom', rain.value) console.log('循环操dom第一个', rain.value[6]) }) onBeforeUpdate(() => { }) onUpdated(() => { }) return { rain, single } },})</script>
输出结果:
vue3 和 vue2 对比操作ref:
1.在 Vue 2 中,在 v-for 里使用的 ref attribute 会用 ref 数组填充相应的 $refs property。 当存在嵌套的 v-for 时,这种行为会变得不明确且效率低下。
2.在 Vue 3 中,这样的用法将不再在 $ref 中自动创建数组。要从单个绑定获取多个 ref,请将 ref 绑定到 一个更灵活的函数上 (这是一个新特性)