天天看點

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: 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官網

繼續閱讀