0
点赞
收藏
分享

微信扫一扫

Vue3传送门Teleport示例

无愠色 2022-07-12 阅读 27


teleport

​teleport​​​可以让我们的子组件​​DOM​​​不用嵌套在父组件的​​DOM​​中,但又可以继续访问父组件的值和方法

子组件,用teleport包裹,这里的​​to​​​对应的是​​App.vue​​里面的id

<template>
<teleport to="#title">
<div class="box">
<slot>标题</slot>
</div>
<div class="placehoder"></div>
</teleport>
</template>
<script>export default {};</script>
<style lang='less' scoped>.box {
width: 100%;
height: 50px;
position: fixed;
top: 0;
left: 0;
background: #fff;
z-index: 1;
box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
display: flex;
align-items: center;
justify-content: center;
font-size: 25px;
}

.placehoder {
width: 100%;
height: 50px;
}</style>

App.vue

<div id="app"></div>
<div id="title"></div>

父组件进行引入

<template>
<div>
<navbar>{{ title }}</navbar>
</div>
</template>

<script>import { reactive, toRefs } from "vue";
import navbar from "../../components/navbar";
export default {
components: {
navbar,
},
setup() {
const that = reactive({
title: "main页",
});
return {
...toRefs(that),
};
},
};</script>

可以看到浏览器渲染出来的是父子组件DOM分离的

Vue3传送门Teleport示例_嵌套


举报

相关推荐

0 条评论