Vue3內置組件Teleport使用方法詳解
前言:
Vue 3.0 新增了一個內置組件 teleport ,主要是為了解決以下場景:
有時組件模板的一部分邏輯上屬于該組件,而從技術角度來看,最好將模板的這一部分移動到 DOM 中 Vue app 之外的其他位置
場景舉例:一個 Button ,點擊后呼出模態(tài)對話框
這個模態(tài)對話框的業(yè)務邏輯位置肯定是屬于這個 Button ,但是按照 DOM 結構來看,模態(tài)對話框的實際位置應該在整個應用的中間
這樣就有了一個問題:組件的邏輯位置和DOM位置不在一起
按照以前 Vue2 的做法,一般是使用 position: fixed; 等CSS屬性強行把對話框定位到了應用的中間位置,屬于沒有辦法的辦法,下面展示下 teleport 的基礎用法。
1、Teleport用法
用法非常簡單,只需要使用 to 這個屬性就可以把組件渲染到想要的位置
// 渲染到body標簽下
<teleport to="body">
<div class="modal">
I'm a teleported modal!
</div>
</teleport>
也可以使用:
<teleport to="#some-id" /> <teleport to=".some-class" /> <teleport to="[data-teleport]" />
必須是有效的查詢選擇器或 HTMLElement
進一步
2、完成模態(tài)對話框組件
現(xiàn)在我們來封裝一個標準的模態(tài)對話框
<template>
<teleport to="body">
<transition name="dialog-fade">
<div class="dialog-wrapper" v-show="visible">
<div class="dialog">
<div class="dialog-header">
<slot name="title">
<span class="dialog-title">
{{ title }}
</span>
</slot>
</div>
<div class="dialog-body">
<slot></slot>
</div>
<div class="dialog-footer">
<slot name="footer">
<button @click="onClose">關閉</button>
</slot>
</div>
</div>
</div>
</transition>
</teleport>
</template>
<script>
import { defineComponent } from 'vue';
export default defineComponent({
name: 'tdialog'
});
</script>
<script setup>
const props = defineProps({
title: String,
visible: Boolean
});
const emit = defineEmits(['close']);
const onClose = () => {
emit('close');
};
</script>
使用的時候,只需要
<t-dialog title="LGD是不可戰(zhàn)勝的" :visible="visible" @close="onClose"> 這是一段內容,蕭瑟仙貝。 </t-dialog>
// ...
const visible = ref(false);
const onDialog = () => {
visible.value = !visible.value;
};
const onClose = () => {
visible.value = false;
};
更進一步
3、組件的渲染
上面我們已經(jīng)把標準的模態(tài)對話框組件完成了,還有另外一種相似的,只需要展示少量文字的輕量級提示組件 Message
在上面的例子中,我們總是把 TDialog 組件寫在使用的地方,但是這個 Messgae 組件,我們在想提示的時候使用一個js語句就把它呼出來,類似于下面的這樣
// 呼出一個提示
Message({ message: '這是一條Message消息' });
想使用一個函數(shù)呼出來,我們需要準備下這個函數(shù),這個函數(shù)的作用就是完成組件的渲染。
const Message = options => {
// 準備渲染容器
const container = document.createElement('div');
// 生成vnode
const vnode = createVNode(MessageConstructor, options);
// 渲染
render(vnode, container);
};
MessageConstructor 是什么?就是我們的SFC(單文件組件):
<template>
<teleport to="#app">
<transition name="message-fade">
<div v-show="visible" ref="ins" class="message" :style="customStyle">{{ message }}</div>
</transition>
</teleport>
</template>
在線 體驗
查看 代碼
總結:
以上就是關于 teleport 組件的基礎用法和擴展用法,給我們提供了不少的方便,到此這篇關于Vue3內置組件Teleport使用方法詳解的文章就介紹到這了,更多相關Vue3內置組件Teleport用法內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue不用import直接調用實現(xiàn)接口api文件封裝
這篇文章主要為大家介紹了vue不用import直接調用實現(xiàn)接口api文件封裝,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06
vue form表單post請求結合Servlet實現(xiàn)文件上傳功能
這篇文章主要介紹了vue form表單post請求結合Servlet實現(xiàn)文件上傳功能,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-01-01

