'How find parent of teleported component in Vue 3?
How can I tell if HTML element that was teleported to body was originnaly in specific component?
Component.vue:
<template>
<div class="parent">
<p>This is parent</p>
<teleport>
<p>This is teleported content</p>
</teleport>
</div>
</template>
Document:
<body>
<div id="app">
<div class="parent">
<p>
This is parent
</p>
</div>
</div>
<p class="teleported">This is teleported</p>
</body>
So now in my code I need to somehow detect that p.teleported is actually inside of Component.vue
What I'm trying to achieve is to detect clicks outside of such components. Existing solutions doesn't work because my components can be nested and teleported multiple times and I have to trace all of them.
Solution 1:[1]
If you need to have a unique tracking for each teleport, you could use data-attribute and set a counter or something for it.
In case you only need to know the name of the parent, you could do set a common attribute or a classname to it.
Component.vue:
<template>
<div class="parent">
<p>This is parent</p>
<teleport to="body">
<p :data-target=`parentName-${counter}`>This is teleported content</p>
</teleport>
</div>
</template>
<template>
<div class="parent">
<p>This is parent</p>
<teleport to="body">
<p data-target="parentName">This is teleported content</p>
<!-- Or you could simply set a classname to it
<p class="parentName">This is teleported content</p> -->
</teleport>
</div>
</template>
Now you can access these by document.querySelectorAll("[data-target]")
and add onclick events to them in the file where you want the magic to happen.
Hope this could be helpful
https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | daniel |
