I have a page in a Vue 3 app which has a scrollable div. The div's content is a recursive component in which there are nodes which might have the node.OptionId field or may not. I would like to have some buttons each for the corresponding OptionIds and whenever I click on the buttons the scrollable div would scroll to the section of the recursive component with the corresponding OptionId.
So for example I have OptionId 001 and if I click the 001 button the div would scroll to the node with the OptionId 001.
However I have no idea how I should implement this behaviour. I tried to apply ref to the nodes but with recursive component only the last node would get the ref attribute and not all the nodes.
the main page:
<div>
<Message
ref="Message"
/>
</div>
the Message component:
<div v-for="(node, i) in message.Content" :key="i">
<MessageContent :node="node" ref="MessageContent" />
</div>
and the recursive MessageContent component:
<template>
<div>
<table>
<thead>
<th
class="label block-title"
v-if="node.Block"
:ref="
node.OptionId !== undefined ? 'OptionId-' + node.OptionId : ''
"
>
{{ node.Name }}
</th>
</thead>
<tbody>
...
</tbody>
</table>
<div v-if="node.Items && node.Items.length">
<MessageContent
v-for="(child, i) in node.Items"
:node="child"
:key="i"
>
</MessageContent >
</div>
</div>
</template>
This way
this.$refs.Message.$refs.MessageContent.$refs
would only come up with the last node's ref which will be 'OptionId-undefined'.
Is there a way in which I could somehow create a custom attribute for the divs with the not undefined OptionIds which I could grab from the main page and use for the scrollIntoView?
This is because your MessageContent is just a single reference kept getting overwritten by v-for items. Vue 3 template refs are just vanilla ref variables. It doesn't have special syntax hence does not have to be this static. The official doc has dedicated section on how to capture template refs inside v-for: https://v3.vuejs.org/guide/composition-api-template-refs.html#usage-inside-v-for