5

I am struggling with the usage of dynamic refs in Vue Composition Api. The Vue guide says I could use it like this:

<div v-for="item in list" :ref="setItemRef"></div>
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
    }
  }
}

But with my code here (shortened):

<template>
    <section
      v-for="(item, i) of storyList"
      :ref="(el) => { if (el) { divs.push(el) } }"
    />
</template>

<script lang="ts">
[...]
export default defineComponent({
  props: {
    storyList: {
      type: Array as () => StoryList,
      required: true,
    },
  },
  setup() {
    const divs = ref([])
    
    return { divs }
  },
})
</script>

... I got only this in my Vue Dev Tools:

data:
divs:Array[0]

$refs:
function(el) { if (el) { _vm.divs.push(el) } }:Array[4]
0:<section id="story-0" class="story-item">
1:<section id="story-1" class="story-item">
2:<section id="story-2" class="story-item">
3:<section id="story-3" class="story-item">

That's not right, isn't it? I should call the refs from divs, not from $refs (what is not working in vue 3), right?

2
  • Check here: stackoverflow.com/questions/66737701/… Commented May 23, 2021 at 12:25
  • 1
    pushing to divs is not a good idea, since you can possibly add more elements (component, DOM refreshes etc.). You should replace elements by index, so you always have right order and exact amount. An there is no need for if check. If you loop storyList and all goes right, you will always generate an element. Replace ref function with this and check if it works :ref="el => divs[index] = el" Commented May 10, 2023 at 10:51

1 Answer 1

0

You don't have reactivity for array so for that use this: reactive([])

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.