英文:
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
上。
<template>
<div>
<component :is="Child" ref="myComp" />
</div>
</template>
<script setup>
import Child from '@/components/Child.vue';
import { ref, onMounted } from 'vue';
const myComp = ref(null);
onMounted(() => {
console.log(myComp.value.$el);
});
</script>
英文:
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
<template>
<div>
<component :is="Child" ref="myComp" />
</div>
</template>
<script setup>
import Child from '@/components/Child.vue';
import { ref, onMounted } from 'vue';
const myComp = ref(null);
onMounted(() => {
console.log(myComp.value.$el);
});
</script>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论