Vue3.0新特性 ---- 標籤 <Teleport>

oxgos發表於2020-10-13

Vue3.0新特性 ---- 標籤 Teleport

用途: 可以控制HTML片段指定在某一父節點下呈現/渲染,而不必訴諸全域性狀態或將其拆分為兩個元件

E.g.

index.html

<body>
  <div id="app" style="position: relative;">
    <h3>Tooltips with Vue 3 Teleport</h3>
    <div>
      <modal-button></modal-button>
    </div>
  </div>
</body>
--------------------------------------------------------

Component.js

const app = Vue.createApp({});
app.component('modal-button', {
  template: `
    <button @click="modalOpen = true">
        Open full screen modal! (With teleport!)
    </button>
    <teleport to="body">
       <div v-if="modalOpen" class="modal">
         <div>
           I'm a teleported modal! 
           (My parent is "body")
           <button @click="modalOpen = false">
              Close
            </button>
        </div>
      </div>
    </teleport>
  `,
  data() {
    return { 
      modalOpen: false
    }
  }
})
app.mount('#app')
--------------------------------------------------------

index.css

.modal {
  position: absolute;
  top: 0; right: 0; bottom: 0; left: 0;
  background-color: rgba(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: center;
  background-color: white;
  width: 300px;
  height: 300px;
  padding: 5px;
}

由上面例子可以看出:
正常狀態下,modal-button是基於#app元素定位的
示例一但在加了標籤< teleport to=“body”>後,就轉變為基於body元素定位了
示例二
接收引數props:

to
/* 必傳
 * @params {string} 指定一個有效的選擇器
*/
disabled
/* 非必傳
 * @params {boolean} 可控制teleport是否失效
*/

相關文章