現(xiàn)在花錢做那個網(wǎng)站好呀北京搜索優(yōu)化排名公司
<Teleport></Teleport>
作用目的:
用于將指定的組件或者元素傳送到指定的位置;
通常是自定義的全局通用彈窗,綁定到 body 上,而不是在當前元素上面;
使用方法:
接收兩個參數(shù)
to: 要將目標傳到的位置; 可以是指定的元素、class、id
disabled: 是否禁止將目標傳送到指定位置;Boolean
比如:
<Teleport
to="body"
disabled="true"
></Teleport>
而為什么要使用teleport 內(nèi)置組件呢?
比如:有這樣一個需求,我們需要一個盒子順時針旋轉(zhuǎn) 45度;而這個盒子同時是一個彈窗的父級組件,并且這個盒子可以打開改彈窗;
父組件:
<template>
<div class="my-built-in"><!-- 內(nèi)置組件 --><div class="other-place" @click="handleOpen">其他dom位置<TelDialog :isShowTel="isShowTel":telCon="telCon" @onCloseDialog="handleClose"></TelDialog></div>
</div>
</template>
<script setup>
import { ref, reactive } from 'vue'
import TelDialog from './components/telDialog.vue'
const isShowTel = ref(false)
const telCon = ref('This is a Teleport component.')
const handleClose = () => {isShowTel.value = false
}
const handleOpen = () => {isShowTel.value = true
}
</script>
<style lang='scss' scoped>
.my-built-in{position: relative;width: 100px;height: 100px;background-color: #00ff00;left: 200px;transform: rotate(45deg);
}</style>
彈窗組件:
<template><div class="my-tel-container" v-if="props.isShowTel"><div class="my-tel-title">Teleport 彈窗</div><div class="my-tel-content">{{ props.telCon }}</div><div class="my-tel-foot"><el-button type="primary" class="close-btn" @click="handleClose">關閉teleport 彈窗</el-button></div></div>
</template>
<script setup>
import { ref } from 'vue'
const props = defineProps({isShowTel:{type: Boolean,default: false,},telCon: {type: String,default: ''}
})
const emits = defineEmits(['onCloseDialog'])
const handleClose = () => {emits('onCloseDialog')
}
</script>
<style lang='scss' scoped>
.my-tel-container{position: fixed;top:50%;left: 50%;width: 440px;height: auto;background-color: aqua;box-shadow: 0 2px 4px 0 rgba(0,0,0, .3);box-sizing: border-box;padding: 0 16px 16px;.my-tel-title{width: 100%;height: 46px;text-align: center;line-height: 46px;font-size: 16px;color: #333;}.my-tel-content{width: 100%;height: 200px;}.my-tel-foot{width: 100%;height: 46px;display: flex;justify-content: right;align-content: center;}
}
</style>
我們會發(fā)現(xiàn)寫好之后在沒有使用teleport 組件的情況下 彈窗也跟著旋轉(zhuǎn)了45度,這并不是我們想要的;為什么會出現(xiàn)這種情況呢?
如圖:
我們需要的是即使父組件發(fā)上了旋轉(zhuǎn) 位移等,彈窗依然是位于瀏覽器的正中央;
此時我們就可以通過 <Teleport></Teleport>
組件來將彈窗組件實際渲染的位置更改到 body 上;但是這樣并不影響 組件直接的通訊;
更改父組件為:
<template>
<div class="my-built-in"><!-- 內(nèi)置組件 --><div class="other-place" @click="handleOpen">其他dom位置<!-- **只需要添加 Teleport 組件即可,disabled 接收一個布爾值,默認是false,true代表不傳送到指定位置 body上** --><Teleport to="body" :disabled="false"><TelDialog :isShowTel="isShowTel":telCon="telCon" @onCloseDialog="handleClose"></TelDialog></Teleport></div>
</div>
</template>
注意事項:
a、在使用teleport 組件時,需要確保傳送的位置dom已經(jīng)渲染完成,即to的位置dom已完成渲染,否則將無法實現(xiàn)傳送;
b、同時可以通過給disabled 動態(tài)傳入一個Boolean 值,來控制是否要將元素或dom傳送到指定的位置;