Currently, I am utilizing Quasar (quasar.dev) in conjunction with Vue2 + Composition API and attempting to access DOM elements that have dynamically generated 'v-bind:ref' properties. This approach is based on the information provided in this section of the Vue3 documentation:
https://v3.vuejs.org/guide/composition-api-template-refs.html#usage-inside-v-for
To better illustrate the issue, I have created a simplified representation on codesandbox: https://codesandbox.io/s/suspicious-pine-90qgd?file=/src/components/MyOuterComponent.ts
The template for my component (MyOuterComponent.vue):
<template>
<div>
<my-component
v-for="(item, i) in list"
v-bind:ref="
(el) => {
if (el) divs[i] = el
}
"
v-bind:key="i"
>
{{ item }}
</my-component>
</div>
</template>
<script src='./MyOuterComponent.ts' />
Here is the script for the component:
import MyComponent from './MyComponent.vue'
import TMyComponent from './MyComponent'
import {
defineComponent,
onMounted,
ref,
reactive,
onBeforeUpdate
} from '@vue/composition-api'
export default defineComponent({
name: 'MyOuterComponent',
components: { MyComponent },
props: {},
setup(props, context) {
const list = reactive([1, 2, 3, 4, 5])
const divs = ref<InstanceType<typeof TMyComponent>[]>([])
// Ensure the refs are reset before each update
onBeforeUpdate(() => {
divs.value = []
})
onMounted(() => {
context.root.$nextTick(() => {
console.log('THE COMPONENTs', divs, context.root.$refs)
divs.value.forEach((div) => {
console.log('My Div Ref: ', div)
})
})
})
return {
list,
divs
}
}
})
According to the documentation, I anticipate that divs
will contain the template refs for my dynamically generated components, thanks to this line in my template:
v-bind:ref="(el) => { if (el) divs[i] = el }"
Despite logging after nextTick, divs
remains empty. I was hoping to see 5 items referencing DOM elements within it.
If I modify the template to the following:
<template>
<div>
<my-component
v-for="(item, i) in list"
v-bind:ref="item"
v-bind:key="i"
>
{{ item }}
</my-component>
</div>
</template>
<script src='./MyOuterComponent.ts' />
In this case, I can locate the refs in context.refs
, although I have been informed that this feature will be eliminated in Vue3. Can someone kindly point out where I may have made an error? Thank you.