我們在做vue2項目的時候,往往彈窗設置都挺負責的需要各種z-indx,而vue3推薦的做法是使用Teleport
<!-- index.html--> <body> <div id="app"></div> <div id="teleport-target"></div> <script type="module" src="/src/main.ts"></script> </body>
在組件內
<template> <p>我是設置頁面a</p> <button @click="showToast" class="btn">打開 toast</button> <!-- to 屬性就是目標位置 --> <teleport to="#teleport-target"> <div v-if="visible" class="toast-wrap"> <div class="toast-msg">我是一個 Toast 文案</div> </div> </teleport> </template> <script setup lang="ts"> import { getCurrentInstance, inject, watch, ref } from 'vue'; // 子組件 const instance = getCurrentInstance() const _this = instance.appContext.config.globalProperties // 獲取全局對象\ const name = inject('name') watch(name, (newValue, oldValue) => { console.log(name.value) }) // toast 的封裝 const visible = ref(false); let timer; const showToast = () => { visible.value = true; // clearTimeout(timer); // timer = setTimeout(() => { // visible.value = false; // }, 2000); } </script> <style> </style>
然後引入這個組件,設置一下樣式就好了,父組件傳遞的props也可以使用