英文:
Assigning refs to Vue 3 components after the parent has mounted
问题
我有一个像这样的Vue组件:
<script setup>
// ...imports
const entries = ref([]);
const entryComponentsRefs = ref([]);
onMounted(async () => {
entries.value = await fetchEntries()
});
</script>
<template>
<Container>
<Entry v-for="entry in entries" :key="entry.id" ref="entryComponentsRefs" />
</Container>
</template>
现在,我想实现一个条目搜索功能,可以使用条目的ref
将<Container>
自动滚动到所选的搜索结果。但是,即使在entries
已经填充并且<Entry>
已经显示出来之后,entryComponentsRefs
仍然为空。
这里有什么问题吗?
英文:
I have a Vue component like this:
<script setup>
// ...imports
const entries = ref([]);
const entryComponentsRefs = ref([]);
onMounted(async () => {
entries.value = await fetchEntries()
});
</script>
<template>
<Container>
<Entry v-for="entry in entries" :key="entry.id" ref="entryComponentsRefs" />
</Container>
</template>
Now, I want to implement an entry search that would autoscroll the <Container>
to the selected search result, using the entry's ref
. But entryComponentsRefs
remains empty even after entries
is already populated and the <Entry>
's already show up.
Is there anything wrong with this?
答案1
得分: 1
当你更新数据时,你需要等待Vue更新DOM:
https://vuejs.org/api/general.html#nexttick
onMounted(async () => {
entries.value = await fetchEntries()
await nextTick();
// 在这里进行DOM操作
});
英文:
When you update your data you need to wait Vue to update DOM:
https://vuejs.org/api/general.html#nexttick
onMounted(async () => {
entries.value = await fetchEntries()
await nextTick();
// do your DOM work here
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论