[Vue.js 3.0] Migration – v-for Array Refs

# v-for Array Refs


breaking

In Vue 2, using the ref attribute inside v-for will populate the corresponding $refs property with an array of refs. This behavior becomes ambiguous and inefficient when there are nested v-fors present.

In Vue 3, such usage will no longer automatically create an array in $refs. To retrieve multiple refs from a single binding, bind ref to a function which provides more flexibility (this is a new feature):

<div v-for="item in list" :ref="setItemRef"></div>

With Options API:

export default {
data() {
return {
itemRefs: []
}
},
methods: {
setItemRef(el) {
if (el) {
this.itemRefs.push(el)
}
}
},
beforeUpdate() {
this.itemRefs = []
},
updated() {
console.log(this.itemRefs)
}
}

With Composition API:

import { onBeforeUpdate, onUpdated } from 'vue'
export default {
setup() {
let itemRefs = []
const setItemRef = el => {
if (el) {
itemRefs.push(el)
}
}
onBeforeUpdate(() => {
itemRefs = []
})
onUpdated(() => {
console.log(itemRefs)
})
return {
setItemRef
}
}
}

Note that:

  • itemRefs doesn't have to be an array: it can also be an object where the refs are set by their iteration keys.

  • This also allows itemRefs to be made reactive and watched, if needed.

以上是[Vue.js 3.0] Migration – v-for Array Refs的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>