这是我参与8月更文挑战的第13天,活动详情查看:8月更文挑战
这篇文章我们来讲一下最后一个内置组件teleport的使用方法,在使用它们的时候我们又该注意什么呢,下面让我们一探究竟把。
为什么使用 teleport
我们在Vue中可以通过将 UI 和相关行为封装到组件中来构建 UI。我们也可以层级嵌套,说白了就是元素或组件可以一层套一层,形成一个UI树。
然而,有时组件模板的一部分逻辑上属于该组件,而从技术角度来看,最好将模板的这一部分移动到 DOM 中 Vue app 之外的其他位置。例如:
创建一个包含全屏模式的组件。在大多数情况下,你希望模态框的逻辑存在于组件中,但是模态框的快速定位就很难通过 CSS 来解决,或者需要更改组件组合。这个时候我们就可以用teleport来解决这个问题。
如何使用
teleport有两个Prop:to 和 disabled。
-
to-string。需要 prop,必须是有效的查询选择器或 HTMLElement (如果在浏览器环境中使用)。使用to九可以把teleport包裹的内容传送到指定元素内。 -
disabled-boolean。此可选属性可用于禁用<teleport>的功能,这意味着teleport包裹的内容会在当前的位置,不会发生改变。
to
使用to传送到指定元素内,如下:
渲染前
<div id="app">
<h1>
<teleport to="#app">
<span>{{title}}</span>
</teleport>
</h1>
</div>
渲染后
<div id="app" data-v-app="">
<span>Hi, world!</span>
<h1><!--teleport start--><!--teleport end--></h1>
</div>
通过上述代码,你是不是发现 span跑到了div#app下面了,这就是teleport的作用。
disabled
使用to可以让teleport禁止传送,就好像施了定身术一样,如下:
渲染前
<div id="app">
<h1>
// 此处多了 disabled
<teleport to="#app" :disabled="true">
<span>{{title}}</span>
</teleport>
</h1>
</div>
渲染后
<div id="app" data-v-app="">
<h1>
<!--teleport start-->
<span>Hi, world!</span>
<!--teleport end-->
</h1>
</div>
让:disabled="true"就可以禁止teleport的功能了。
结合 components 使用
我们可以把teleport用到components中,自定义两个组件,如下:
my-component-child
app.component('my-component-child', {
props:['name'],
template: `<span>{{name}}</span>`
})
my-component
app.component('my-component', {
template: `<h1>
<span>hello</span>
<teleport to="#app">
<my-component-child name="world"></my-component-child>
</teleport>
</h1>`
})
这里我们需要注意的是:即使在不同的地方渲染 my-component-child,它仍将是 my-component 的子级,并将从中接收 name prop。
在同一目标上使用多个 teleport
有时我们会有这样的需求:需要多个 <teleport> 组件将其内容挂载到同一个目标元素上。顺序将是一个简单的追加——稍后挂载将位于目标元素中较早的挂载之后。如下:
渲染前
<div id="app">
<h3>
<teleport to="#app">
<h1>hello</h1>
</teleport>
<teleport to="#app">
<h1>world</h1>
</teleport>
</h3>
</div>
渲染后
<div id="app" data-v-app="">
<h1>hello</h1>
<h1>world</h1>
<h3>
<!--teleport start--><!--teleport end-->
<!--teleport start--><!--teleport end-->
</h3>
</div>
总结
teleport在实际开发中是非常使用的,我们可以更方面的处理一些需求。
比如我需要一个全屏功能但是,要在它的父级或者其他级显示,我们就可以用teleport。如果不用它,我们需要写很多复杂的逻辑来实现这个功能。
想了解更多文章,传送门已开启:回首Vue3目录篇 !