如何在Vue 3的父组件中访问子组件的根元素

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

How to access root element of child component in parent component in Vue 3

问题

我知道defineExpose函数,但它似乎是一种不好的做法,所以我正在寻找可能帮助我的正确解决方案。提前回答一个问题 - 是的,我确实需要它,因为我的父组件中有一个v-for,每次迭代都会导入动态组件,并将其传递给:is属性中的<component>元素。我需要实现自定义的拖放逻辑,因此我需要子组件的根HTML元素。

英文:

I do know about defineExpose function, but it seems to be a bad practice, so I'm looking for proper solution which may help me.
Answering a question in advance - yes, I really need in since there is v-for in my parent component with dynamic component imports for each iteration which I pass to the <component> element in :is attribute.
I need to implement custom drag and drop logic so I need root HTML element of child component.

答案1

得分: 0

如果你需要根HTML元素,你可以给你的组件分配一个ref,一旦组件被挂载,就可以访问它,HTML本身位于 refName.value.$el 上。

&lt;template&gt;
  &lt;div&gt;
    &lt;component :is=&quot;Child&quot; ref=&quot;myComp&quot; /&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script setup&gt;
import Child from &#39;@/components/Child.vue&#39;;
import { ref, onMounted } from &#39;vue&#39;;

const myComp = ref(null);

onMounted(() =&gt; {
  console.log(myComp.value.$el);
});
&lt;/script&gt;
英文:

If you need root HTML element you can assign a ref to your component, which is accessable once the component is mounted, and the HTML itself is on refName.value.$el

&lt;template&gt;
  &lt;div&gt;
    &lt;component :is=&quot;Child&quot; ref=&quot;myComp&quot; /&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script setup&gt;
import Child from &#39;@/components/Child.vue&#39;;
import { ref, onMounted } from &#39;vue&#39;;

const myComp = ref(null);

onMounted(() =&gt; {
  console.log(myComp.value.$el);
});
&lt;/script&gt;

huangapple
  • 本文由 发表于 2023年4月7日 03:21:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75953044.html
匿名

发表评论

匿名网友

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

确定