teleport組件
teleport翻譯過(guò)來(lái)的意思是遠(yuǎn)程傳送裤翩。
teleport組件是vue3中的一個(gè)內(nèi)置組件红选,實(shí)現(xiàn)的就是將一個(gè)元素傳送給指定的DOM節(jié)點(diǎn)下长赞。
teleport組件使用
這里拿我們經(jīng)常用到的模態(tài)框做實(shí)例
我們先看看不使用 teleport組件的效果
// 父組件
<modal title="提示彈窗" :visible="isShowModal" @close="closeModal">
<div>這是一個(gè)modal框涣澡,會(huì)瞬移</div>
</modal>
// 子組件 modal
<template>
<div v-if="visible" class="v3-modal">
<h2 class="v3-modal-title">{{ title }}</h2>
<div class="v3-modal-content">
<slot>This is a modal</slot>
</div>
<button @click="handleClose">close</button>
</div>
</template>
測(cè)試可以看到子組件modal是渲染在#app內(nèi)的
modal渲染.png
使用teleport瞬移組件到指定的dom中
首先在項(xiàng)目的/public/index.html中加入一個(gè)元素惠爽,作為teleport組件的接收容器
<body>
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
// teleport 容器
<div id="modal"></div>
</body>
然后給modal組件套上<teleport></teleport>,并設(shè)置to屬性指定容器,代碼如下
<template>
<teleport to="#modal">
<div v-if="visible" class="v3-modal">
<h2 class="v3-modal-title">{{ title }}</h2>
<div class="v3-modal-content">
<slot>This is a modal</slot>
</div>
<button @click="handleClose">close</button>
</div>
</teleport>
</template>
最后我們看看渲染的效果沥曹,modal組件已經(jīng)瞬移到#modal下了
teleport渲染效果.png
以上就是vue3中teleport的知識(shí)啦份名,歡迎評(píng)論區(qū)補(bǔ)充~~