portal-vue 在Vue中的使用
引文使用过React的同学可能知道,在目前React的版本中可以找到一个叫Portals的相关API.那么这potrol是用来干什么的? 下面看一下它的使用说明Portals 提供了一种很好的将子节点渲染到父组件以外的 DOM 节点的方式。第一个参数(child)是任何可渲染的 React 子元素,例如一个元素,字符串或碎片。第二个参数(container)则是一个 DOM 元素。Rea...
引文
使用过React的同学可能知道,在目前React的版本中可以找到一个叫Portals
的相关API.
那么这Portals是用来干什么的? 下面看一下它的使用说明
Portals 提供了一种很好的将子节点渲染到父组件以外的 DOM 节点的方式。
第一个参数(child)是任何可渲染的 React 子元素,例如一个元素,字符串或碎片。第二个参数(container)则是一个 DOM 元素。
React中的用法
通常讲,当你从组件的 render 方法返回一个元素,该元素仅能装配 DOM 节点中离其最近的父元素:
render() {
// React mounts a new div and renders the children into it
return (
<div>
{this.props.children}
</div>
);
}
然而,有时候将其插入到 DOM 节点的不同位置也是有用的:
render() {
// React does *not* create a new div. It renders the children into `domNode`.
// `domNode` is any valid DOM node, regardless of its location in the DOM.
return ReactDOM.createPortal(
this.props.children,
domNode,
);
}
对于 portal
的一个典型用例是当父组件有 overflow: hidden
或 z-index
样式,但你需要子组件能够在视觉上“跳出(break out)”其容器。例如,对话框、hovercards以及提示框:
注意:
记住这点非常重要,当在使用 portals时,你需要确保遵循合适的可访问性。
portal-vue 引入
在React中我们使用Portals
来实现上文的需求,那么在Vue中如何实现上文的需求呢,经查验vue官网并没有提供portal
相关的东西,于是便有了portal-vue
这个库
portal-vue是什么?
简单来说PortalVue
包含两个组件,portal
组件和portal-target
组件,他允许你将portal
组件中的内容转至portal-target
组件所在的地方.
更好的理解可以看官网的这句话
PortalVue is a set of two components that allow you to render a component’s template (or a part of it) anywhere in the document - even outside the part controlled by your Vue App!
安装配置
npm install --save portal-vue
# or with yarn
yarn add portal-vue
import PortalVue from 'portal-vue'
Vue.use(PortalVue)
portal-vue 这么用
下面简述几个例子
基本使用
<portal to="destination">
<p>This slot content will be rendered wherever the <portal-target> with name 'destination'
is located.
</p>
</portal>
<portal-target name="destination">
<!--
This component can be located anwhere in your App.
The slot content of the above portal component will be rendered here.
-->
</portal-target>
在高级使用里面还可以进行配置以及与相关指令进行配合使用,其中动画、插槽也是可以根据需求来选择使用的.
portal-vue官网
更多推荐
所有评论(0)