# 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>
1

With Options API:

export default {
  data() {
    return {
      itemRefs: []
    }
  },
  methods: {
    setItemRef(el) {
      this.itemRefs.push(el)
    }
  },
  beforeUpdate() {
    this.itemRefs = []
  },
  updated() {
    console.log(this.itemRefs)
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

With Composition API:

import { ref, onBeforeUpdate, onUpdated } from 'vue'

export default {
  setup() {
    let itemRefs = []
    const setItemRef = el => {
      itemRefs.push(el)
    }
    onBeforeUpdate(() => {
      itemRefs = []
    })
    onUpdated(() => {
      console.log(itemRefs)
    })
    return {
      itemRefs,
      setItemRef
    }
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

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.

Deployed on Netlify.
Last updated: 9/18/2020, 1:09:21 AM