[Vuejs]-How to properly create a popup component in Vue 3

0👍

Here is my solution, which was inspired by a comment on my question and which I think is worth sharing.

Instead of putting the target element into a slot, I am now passing its ref as a prop, which makes things much cleaner.

The popover component’s template now looks like this.

<template>
  <teleport to="body">
    <div v-show="show" class="modal" ref="modal">
      <div ref="popover" class="popover" :style="{top: popoverTop + 'px', left: popoverLeft + 'px'}">
        <slot ref="content"></slot>
      </div>
    </div>
  </teleport>
</template>

I has a targetRefprop, so the component can be simply used like this:

<div ref="myTargetElement" @click="isPopupVisible=true">
</div>
<modal :show="isPopupVisible" @close="isPopupVisible=false" targetRef="myTargetElement">
    <!-- popup content goes here -->
</modal>

And after mounting I can access the target element like this:

let targetElement = this.$parent.$refs[this.targetRef];

I like this solution a lot. However, ideas, advice or words of caution are still highly welcome.

Leave a comment