前提
Vue鼓励我们通过将UI和相关行为封装到组件中来构建UI。我们可以将它们嵌套在另一个内部,来构建一个组成应用程序UI树。

然而,有时组件模板的一部分逻辑上属于该组件,而从技术角度来看,最好将模板的这一部分移动到DOM中Vue app之外的其他位置。
Teleport提供了一种干净的方法,允许我们控制在DOM中哪个父节点下渲染HTML,而不必求助于全局状态或将其拆分为两个组件。
- app.component('modal-button', {
- template: `
- Open full screen modal! (With teleport!)
- I'm a teleported modal!
- (My parent is "body")
- Close
- `,
- data() {
- return {
- modalOpen: false
- }
- }
- })
使用
与Vue compoents一起使用
如果
- const app = Vue.createApp({
- template: `
Root instance
- `
- })
- app.component('parent-component', {
- template: `
This is a parent component
- `
- })
- app.component('child-component', {
- props: ['name'],
- template: `
Hello, {{ name }}- `
- })
在这种情况下,即使在不同地方渲染child-compoents,它仍将是parent-component的子集,并将从中接受name prop。
这也意味着来自父组件的注入按预期工作,并且子组件将嵌套在Vue Devtools中的父组件之下,部署放在实际内容移动到的位置。
在同一目标上使用多个teleport
一个常见的用例场景是一个可重用的
A B A B
使用
to:String。需要prop,必须是有效的查询选择器或HTMLElement(如果在浏览器环境中使用)。指定将在其移动
disabled: boolean。此可选属性可用于禁用
值得注意的是,这将移动实际的DOM节点,而不是被销毁和重新创建,而且它还将保持
任何组件实例的活动状态。所有有状态的HTML元素(即播放的视频)都将保持其状态。
本文题目:Vue3值得注意的新特性之——teleport
URL地址:http://www.jxjierui.cn/article/coojdgj.html


咨询
建站咨询
