当前位置: 代码迷 >> 综合 >> Vue3.0新特性 ---- 标签 <Teleport>
  详细解决方案

Vue3.0新特性 ---- 标签 <Teleport>

热度:73   发布时间:2024-02-28 06:02:38.0

Vue3.0新特性 ---- 标签 Teleport

用途: 可以控制HTML片段指定在某一父节点下呈现/渲染,而不必诉诸全局状态或将其拆分为两个组件

E.g.

index.html<body><div id="app" style="position: relative;"><h3>Tooltips with Vue 3 Teleport</h3><div><modal-button></modal-button></div></div>
</body>
--------------------------------------------------------Component.jsconst app = Vue.createApp({
    });
app.component('modal-button', {
    template: `<button @click="modalOpen = true">Open full screen modal! (With teleport!)</button><teleport to="body"><div v-if="modalOpen" class="modal"><div>I'm a teleported modal! (My parent is "body")<button @click="modalOpen = false">Close</button></div></div></teleport>`,data() {
    return {
     modalOpen: false}}
})
app.mount('#app')
--------------------------------------------------------index.css.modal {
    position: absolute;top: 0; right: 0; bottom: 0; left: 0;background-color: rgba(0,0,0,.5);display: flex;flex-direction: column;align-items: center;justify-content: center;
}
.modal div {
    display: flex;flex-direction: column;align-items: center;justify-content: center;background-color: white;width: 300px;height: 300px;padding: 5px;
}

由上面例子可以看出:
正常状态下,modal-button是基于#app元素定位的
示例一但在加了标签< teleport to=“body”>后,就转变为基于body元素定位了
示例二
接收参数props:

to
/* 必传* @params {string} 指定一个有效的选择器
*/
disabled
/* 非必传* @params {boolean} 可控制teleport是否失效
*/