vue3.0新特性--Teleport

根据vue官方提供例子构建一个模态框实例,代码如下:

import { createApp } from 'vue/dist/vue.esm-bundler.js'
const app = createApp({});//在这里官方例子是这么书写的:const app = Vue.createApp({});这里我如果还是按照vue2.0,通过import Vue from 'vue';会报错Cannot read property 'createApp' of undefined,所以我换了另一种方式去书写则正常展示
app.component('modal-button', {
template: `
<button @click="modalOpen = true">
Open full screen modal!
</button>
<div v-if="modalOpen" class="modal">
<div>
I'm a modal!
<button @click="modalOpen = false">
Close
</button>
</div>
</div>
`,
data() {
return {
modalOpen: false
}
}
})
app.mount('#app');

当在初始的 HTML 结构中使用这个组件时,我们可以看到一个问题——模态框是在深度嵌套的 div 中渲染的,而模态框的 position:absolute 以父级相对定位的 div 作为引用

Teleport 提供了一种干净的方法,允许我们控制在 DOM 中哪个父节点下渲染了 HTML,而不必求助于全局状态或将其拆分为两个组件,代码如下:

app.component('modal-button', {
template: `
<button @click="modalOpen = true">
Open full screen modal!
</button>
<teleport to="body">
<div v-if="modalOpen" class="modal">
<div>
I'm a modal!
<button @click="modalOpen = false">
Close
</button>
</div>
</div>
</teleport>
`,
data() {
return {
modalOpen: false
}
}
})

使用 <teleport>,并告诉 Vue “Teleport 这个 HTML 到该‘body’标签”

posted @ 2021-02-19 15:13  星马豪  阅读(175)  评论(0编辑  收藏  举报