在 Vue 3 组件的父组件挂载后分配引用

huangapple go评论72阅读模式
英文:

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:

&lt;script setup&gt;
// ...imports

const entries = ref([]);
const entryComponentsRefs = ref([]);

onMounted(async () =&gt; {
  entries.value = await fetchEntries()
});
&lt;/script&gt;

&lt;template&gt;
  &lt;Container&gt;
    &lt;Entry v-for=&quot;entry in entries&quot; :key=&quot;entry.id&quot; ref=&quot;entryComponentsRefs&quot; /&gt;
  &lt;/Container&gt;
&lt;/template&gt;

Now, I want to implement an entry search that would autoscroll the &lt;Container&gt; to the selected search result, using the entry's ref. But entryComponentsRefs remains empty even after entries is already populated and the &lt;Entry&gt;'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 () =&gt; {
  entries.value = await fetchEntries()
  await nextTick();
  // do your DOM work here
});

huangapple
  • 本文由 发表于 2023年7月27日 15:18:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76777319.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定