portal-vue 在Vue中的使用

引文

使用过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: hiddenz-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官网

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值