Teleport的作用和应用场景
Teleport 是一种能够将Teleport所包起来的模板内容移动到文档树中除了Vue关联的app元素之外的其他位置。
应用场景:我们可以在组件的逻辑位置写模板代码,这意味着我们可以使用组件中的数据,然后在 Vue 应用的范围之外渲染它,比如可以实现相对于整个body定位的模态弹窗。
Teleport的使用
Teleport有两个参数:
to为需要移动的指定位置,可以是选择器也可以是DOM节点;disabled如果为true,内容不进行移动,disabled如果为false, 则Teleport包裹的元素节点会被移动到to的节点下。
把需要移动的内容用Teleport包起来即可
实现模态弹窗
<script setup>
// 引入
import { ref, reactive, watch } from "vue";
let title = ref("Teleport");
let isshow = ref(false);
</script>
<template>
<div class="app">
<button @click="isshow = true">点击打开弹窗</button>
<teleport to="body">
<div class="motaibox" v-show="isshow">
<div class="box">
<h1>{{ title }}---实现模态弹窗</h1>
<button @click="isshow=false">点击关闭弹窗</button>
</div>
</div>
</teleport>
</div>
</template>
<style scoped lang='scss'>
.motaibox {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
background-color: rgba(206, 206, 206, 0.621);
.box {
width: 300px;
height: 600px;
background-color: goldenrod;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
}
</style>
直接操作DOM元素
<div class="box">
<div ref="drag" class="box_drag">我会被拖动</div>
</div>
</template>
<script setup>
import { onMounted, ref } from 'vue'
const drag = ref() //核心,如果这里是ts的话。这个ref是一个泛型ref<你的类型>()
onMounted(() => {
console.log(drag.value)
})
</script>