Teleport in Vue 3

Tram Ho

This article introduces Teleport vue 3 and the same simple modal function

What is teleport in vue 3?

  • <Teleport> is a built-in component in Vue 3 that allows us to “teleport” (transpose) part of a component’s template to a DOM node that exists outside of the component’s DOM structure.
  • It has a prop : to and a default slot which shows the position content to be displayed in the DOM element mentioned in prop to.
  • Disabling Teleport : use prop disabled

Example:

  • Example of making a modal written in vue 3, ts, tailwind
  • <script setup> section: This is a new feature in Vue 3 that allows you to write component logic without having to declare variables and functions using concise declarations like ref, defineProps, and defineEmits.
  • Import: The line import { ref } from ‘vue’; import ref from the Vue library to create a ref for the modal element.
  • Import CloseIcon : import the CloseIcon component svg file modal close button.
  • Import the useOnClickOutside function useOnClickOutside from a composable (composable is a logical reuse in Vue) defined in the file click-outside.ts. This function allows us to handle the click event outside of the modal element.
  • Define Props: Line type TPProps = { … }; defines a style for the props received in the modal element. Props include show (which controls modal display), title (modal title), textSubmit (submit button text), and clickToClose (whether or not to allow modal to be closed on click outside).
  • Define Default Props: use defineProps to define props and withDefaults to set default values for props if none are provided.
  • Define Emits: use defineEmits to define the events this component can emit, in this case onSubmit and onClose.
  • Modal Ref: const modalRef = ref<HTMLElement | null>(null); create a ref for the modal element, which will be used in useOnClickOutside to identify the element outside the modal on click.
  • useOnClickOutside(modalRef, () => { … }); use composable useOnClickOutside to handle the click event outside the modal element. When external click and clickToClose is enabled, the onClose event is fired.

Use:

Share the news now