Ref in v-for, can't access it. why?

The code of Vue template is very simple,
The foo ref can access, but the bar can’t access it.
In object of $refs, can see the array of bar, but can’t use this.$refs.bar access it.WHY?

<template>
  <!-- test component-->
  <div class="test" ref="foo">
    <div class="item" v-for="item in items" ref="bar">
      {{item}}
    </div>
  </div>

</template>

<script>
  export default {
    name: "Test",
    props:{
      items:{
        type:Array
      }
    },
    mounted(){
      console.log('test',this.$refs) // OK ,object
      console.log('test',this.$refs.foo)  // Ok HTMLElement
      
      console.log('test',this.$refs.bar)  // undefined, why?
    }
  }
</script>

<style lang='scss'>

</style>

How are you populating your items prop. Through a async nature like an Ajax call from the parent?

Ajax call from the parent. Oh, I see… The data wasn’t OK. The output of browser console is a reference. It’s dynamic Synchronize with the DOM.

1 Like

That would be correct

    mounted () {
    const vm = this
    vm.$nextTick(() => {
        console.log(vm.$refs.bar)
    })
},

I’m having the same problem, how did you solve this? I tried the code above, it still returns undefined :frowning:

are you using vue 2 or vue 3? There was a breaking change regarding template-refs on v-for-loops:
https://v3.vuejs.org/guide/migration/array-refs.html

well in vue 3 you can like store the refs in an array.

<div v-for="item of items" :ref="pushToRefsArr"></div>

`
setup() {
let items = [ “item1”, “item2”, “item3”, “item4” ];
let refsArr = [];
const pushToRefsArr = refDiv => refsArr.push(refDiv);

return { pushToRefsArr, items }

}
`

where pushToRefsArr runs and receive the HTML element as argument while rendering the list.

But you have to reset the refsArr to empty array after each component update.