其他分享
首页 > 其他分享> > 【vue3学习系列】Teleport传送门标签的使用,写个全局对话框

【vue3学习系列】Teleport传送门标签的使用,写个全局对话框

作者:互联网

文章目录

前言

之前在vue2自己手写全局对话框组件的时候,会遇到这种情况:在其他组件引入对话框组件时,容易把对话框组件嵌套的太深,导致对话框组件的css容易被污染和难写混乱,而且对话框既然是全局的,那嵌套在层层组件中也不优雅,容易被干扰。

所以可以用Teleport去解决这个问题。

使用

对话框组件:

<template>
<teleport to="#modal">
  <div id="center" v-if="isOpen">
    <h2><slot>this is a modal</slot></h2>
    <button @click="buttonClick">Close</button>
  </div>
</teleport>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
  props: {
    isOpen: Boolean,
  },
  emits: {
    'close-modal': null
  },
  setup(props, context) {
    const buttonClick = () => {
      context.emit('close-modal')
    }
    return {
      buttonClick
    }
  }
})
</script>
<style>
  #center {
    width: 200px;
    height: 200px;
    border: 2px solid black;
    background: white;
    position: fixed;
    left: 50%;
    top: 50%;
    margin-left: -100px;
    margin-top: -100px;
  }
</style>

直接在index.html加上个标签,把全局对话框组件传送至此:

<div id="app"></div>
<div id="modal"></div>

最后这样调用对话框组件:

const modalIsOpen = ref(false)
const openModal = () => {
  modalIsOpen.value = true
}
const onModalClose = () => {
  modalIsOpen.value = false
}

<button @click="openModal">Open Modal</button><br/>
<modal :isOpen="modalIsOpen" @close-modal="onModalClose"> My Modal !!!!</modal>

代码来源:慕课网

标签:Teleport,const,对话框,传送门,modalIsOpen,modal,组件,全局
来源: https://blog.csdn.net/pagnzong/article/details/120247615