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?
ifcheck. If you loopstoryListand all goes right, you will always generate an element. Replacereffunction with this and check if it works:ref="el => divs[index] = el"