'Use dynamic Refs correctly in Vue 3 (Composition Api)
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?
Solution 1:[1]
You don't have reactivity for array so for that use this:
reactive([])
Solution 2:[2]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Serhii Kucherenko |
| Solution 2 | Ejiro Asiuwhu |
