1. Introduction

In VUe2, the V-for binding $refs automatically generates an array of refs, but in V-for this behavior becomes ambiguous and inefficient. In VUe3, this usage does not work because VUe3 does not automatically generate an array of refs. If we need to fetch an array of refs, we need to manually unbind them using a function.

2. Usage of vue2

<template> <div> <ul> <! Ref -> <li v-for="(item, index) in list" :key="index" ref="liRef"> {{ item }} </li> </ul> </div> </template> <script> export default { name: "App", data() { return { list: [1, 2, 3], }; }, components: {}, mounted() { console.log("ref:", this.$refs.liRef); }}; </script>Copy the code

The printout looks like this:

As you can see, the refs array is automatically generated in VUe2.

3. Usage in vue3

If we were to use vue2 again, we would get the following result:

We can see that vue3 does not automatically generate the refs array, only the ref of the last element. If we need to bind the refs in v-for and generate the refs array, we need to manually bind the refs using a function as follows:

<template> <div> <ul> <! Ref -> <li v-for="(item, index) in list" :key="index" :ref="setItemRef"> {{ item }} </li> </ul> </div> </template> <script> export default { name: "App", data() { return { list: [1, 2, 3], itemRefs: [], }; }, methods: { setItemRef(el) { this.itemRefs.push(el); }, }, beforeUpdate() { this.itemRefs = []; }, mounted() { console.log("ref:", this.itemRefs); }, updated() { // console.log(this.itemRefs); }}; </script>Copy the code

The ref is bound to a setItemRef function, and what setItemRef does is el push into the itemRefs array.

Now the results are similar to those in VUe2.

4. New features of vue3 Array Refs

Now an itemRefs doesn’t have to be an array, it could be an object.

setItemRef(el) {
  // this.itemRefs.push(el);
  // itemRefs in data need to be defined as objects
  let index = parseInt(Math.random(1) * 1000);
  this.itemRefs[index] = el;
},
Copy the code

With this simple instance rewriting, you can define An itemRefs as an object.