1. 程式人生 > 程式設計 >vue3 Teleport瞬間移動函式使用方法詳解

vue3 Teleport瞬間移動函式使用方法詳解

vue3 Teleport瞬間移動函式的使用,供大家參考,具體內容如下

Teleport一般被翻譯成瞬間移動元件,實際上是不好理解的.我把他理解成"獨立元件"

他可以那你寫的元件掛載到任何你想掛載的DOM上,所以是很自由很獨立的

以一個例子來看:編寫一個彈窗元件

<template>
<teleport to="#modal">
 <div id="center" v-if="isOpen">
 <h2><slot>this is a modal</slot></h2>
 <button @click="button
程式設計客棧
Click">Close</button> </div> </teleport> </template> <script lang="ts"> export default { props: { isOpen: Boolean,},emits: { 'close-modal': null },setup(props,context) { const buttonClick = () => { context.emit('close-modal') } return { buttonClick } } } </script> &
程式設計客棧
lt;style> #center { width: 200px; height: 200px; 程式設計客棧border: 2px solid black; background: white; position: fixed; left: 50%; top: 50%; margin-left: -100px; margin-top: -100px; } </style>

在app.vue中使用的時候跟普通元件呼叫是一樣的

<template>
<div id="app">
 <img alt="Vue logo" src="./assets/logo.png">
 <HelloWorld msg="Welcome to Your Vue.
js
App"/> <HooksDemo></HooksDemo>WsgdIWTkTG <button @click="openModal">Open Modal</button><br/> <modal :isOpen="modalIsOpen" @close-modal="onModalClose"> My Modal !!!!</modal> </div> </template> <script> import HelloWorld from './components/HelloWorld.vue' import HooksDemo from './components/HooksDemo.vue' import Modal from './components/Modal.vue' import{ref} from 'vue' export default { name: 'App',components: { HelloWorld,HooksDemo,Modal },setup() { const modalIsOpen = ref(false) const openModal = () => { modalIsOpen.value = true } const onModalClose = () => { modalIsOpen.value = false } return { modalIsOpen,openModal,onModalClose } } } </script> <style> #app { font-family: Avenir,Helvetica,Arial,sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>

要是在app.vue檔案中使用的時候,modal是在app的 DOM節點之下的,父節點的dom結構和css都會給modal產生影響
於是產生的問題

1.modal被包裹在其它元件之中,容易被幹擾
2.樣式也在其它元件中,容易變得非常混亂

Teleport 可以把modal元件渲染到任意你想渲染的外部Dom上,不必巢狀在#app中,這樣就可以互不干擾了,可以把Teleport看成一個傳送門,把你的元件傳送到任何地方
使用的時候 to屬性可以確定想要掛載的DOM節點下面

<template>
 <teleport to="#modal">
 <div id="center">
 <h2>柏特better</h2>
 </div>
 </teleport>
</template>

在public資料夾下的index.html中增加一個節點

<!DOCTYPE html>
<html lang="en">
 <head>
 <meta charset="utf-8">
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <meta name="viewport" content="width=device-width,initial-scale=1.0">
 <link rel="icon" href="<%= BASE_URL %>favicon.ico" >
 <title><%= htmlWebpackPlugin.options.title %></title>
 </head>
 <body>
 <noscript>
 <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without javascript enabled. Please enable it to continue.</strong>
 </noscript>
 <div id="app"></div>
 <div id="modal"></div>
 <!-- built files will be auto injected -->
 </body>
</html>

這樣可以看到modal元件就是沒有掛載在apwww.cppcns.comp下,不再受app元件的影響了

vue3 Teleport瞬間移動函式使用方法詳解

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。