Trying to get dynamically created ref
I'm trying to get ref that are dynamically created but it doesn't work very well
In my template i have :
where i'm creating a :ref=section-${indexsection} and index_section is 0,1,2,3etc
Then in my script i have:
But the console.log(document.querySelector([ref="section-${index}"]) ) give me null, as like it didn't has any ref section-0 for example, but there is because my template created it with the :ref=section-${index_section}
2 Replies
Hi @BobLamarley. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
Based on the information provided in the knowledge sources, I can offer some insights into your issue with dynamically created refs in Nuxt/Vue. However, it's important to note that the exact solution may require some adjustments to your specific setup.
The main issue here seems to be related to how you're trying to access the dynamically created refs. In Vue 3 and Nuxt 3, the way refs work with v-for has changed compared to earlier versions. Let's address this step by step:
1. First, when using refs with v-for, you should use a single ref attribute instead of trying to create dynamic ref names. Your template should look like this:
2. In your script section, you're on the right track with defining
sectionRefs
as a ref:
3. To access the refs, you need to use them after the component has mounted. The nextTick()
approach you're using is good, but you don't need to use document.querySelector
. Instead, you can directly access the sectionRefs.value
array. Here's how you might modify your watch function:
This approach is based on the information provided in the Stack Overflow post about accessing refs in v-for (https://stackoverflow.com/questions/76859379).
Additionally, if you need to expose methods or properties from your child components, you should use defineExpose
in the child component, as mentioned in the Stack Overflow post about passing data attributes (https://stackoverflow.com/questions/78622931).
Remember that when working with refs in Vue 3 and Nuxt 3, it's important to access them after the component has mounted and to use the .value
property when working with ref objects.
If you're still having issues after making these changes, it might be helpful to create a minimal reproducible example in a tool like StackBlitz, as suggested in one of the GitHub issue comments (https://github.com/nuxt/nuxt/issues/28942), to get more specific help.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------<@314138038995255298> Kapa.ai is still learning and improving, please let me know how I did by reacting below.