瞬间移动组件(Teleport)

Teleport 是一种能够将我们的模板移动到 DOM 中 Vue app 之外的其他位置的技术。

如果我们嵌套在 Vue app 内的某个组件内部,那么处理嵌套组件的定位、z-index 和样式就会变得很困难。
使用 Teleport 就可以方便的解决组件间 css 层级问题

我们将模态内容包装在 teleport 组件中,
还需要指定一个 to 属性,为该属性分配一个查询选择器,以标识目标元素。

父组件

<template>
  <div id="d1">
    <h3>第一个div</h3>
  </div>
  <div id="d2">
    <h3>第二个div</h3>
  </div>
  <ModalButton></ModalButton>
</template>

<script lang='ts'>
import { reactive, toRefs, onBeforeMount, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'//引入路由
import ModalButton from "../components/1.vue";
export default {
  name: '',
  components: {
    ModalButton
  },
  setup() {
    let router = useRouter(), route = useRoute();
    const data = reactive({
    })
    onBeforeMount(() => {
    })
    onMounted(() => {
    })
    const refData = toRefs(data);
    return {
      ...refData,
    }

  }
};
</script>
<style scoped>
.modal {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: rgba(0, 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: space-around;
  background-color: white;
  width: 350px;
  height: 300px;
  padding: 5px;
}
</style>

子组件

<template>
    <div>
        <button @click="modalOpen = true">弹出一个模态框</button>
        <teleport to="body">
            <div v-if="modalOpen" class="modal">
                <div>
                    这是一个弹框,挂载在 body 元素上。
                    <button @click="modalOpen = false">关闭</button>
                </div>
            </div>
        </teleport>

    </div>
</template>

<script lang='ts'>
import { reactive, toRefs, onBeforeMount, onMounted, defineComponent } from 'vue'
import { useRouter, useRoute } from 'vue-router'//引入路由
export default
    {
        name: '',
        setup() {
            let router = useRouter(), route = useRoute();
            const data = reactive({
                modalOpen: false
            })
            onBeforeMount(() => {
            })
            onMounted(() => {
            })
            const refData = toRefs(data);
            return {
                ...refData,
            }

        }
    };
</script>
<style scoped>
.modal {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background-color: rgba(0, 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: space-around;
    background-color: white;
    width: 350px;
    height: 300px;
    padding: 5px;
}
</style>

你可能感兴趣的:(#,Vue3,#,Vue2,vue.js,javascript,前端)