Skip to content
On this page

渲染 Wrapper 元素

渲染外層 Wrapper

預設 <Float> 不會渲染外層的 Wrapper 元素,比如像以下範例:

html
<Float show>
  <button type="button">button</button>
  <div>content</div>
</Float>

會渲染出以下的 HTML:

html
<button type="button">button</button>
<div>
  <div>content</div>
</div>

因為 <Float> 預設的 astemplate,會直接渲染出子元素。如果想要包裝其他的元素的話,可以傳入其他的 as

html
<Float show as="div">
  <button type="button">button</button>
  <div>content</div>
</Float>

就可以渲染外層的 Wrapper 元素:

html
<div>
  <button type="button">button</button>
  <div>
    <div>content</div>
  </div>
</div>

渲染浮動元素 Wrapper

浮動元素的 Wrapper 可以由 floating-as 設定,預設是 div

html
<Float show>
  <button type="button">button</button>
  <div>content</div>
</Float>

會渲染出以下的 HTML:

html
<button type="button">button</button>
<div>
  <div>content</div>
</div>

如果把 floating-as 設定為 template 時,浮動元素就不會渲染 Wrapper 元素,而直接定位浮動元素本身:

html
<Float show floating-as="template">
  <button type="button">button</button>
  <div>content</div>
</Float>

會渲染出以下的 HTML:

html
<button type="button">button</button>
<div>content</div>

傳入元件 Wrapper

有時會需要在浮動元素的 Wrapper 上增加一些 HTML 屬性或 Class,可以使用 Vue 的 Functional Component

js
import { h, mergeProps } from 'vue'

const Wrapper = (props, { slots }) => {
  return h('div', mergeProps(props, {
    'class': 'wrapper-class',
    'data-label': 'wrapper label',
  }), slots)
}

然後將該元件傳入:

html
<Float show :floating-as="Wrapper">
  <button type="button">button</button>
  <div>content</div>
</Float>

會渲染出以下的 HTML:

html
<button type="button">button</button>
<div class="wrapper-class" data-label="wrapper label">
  <div>content</div>
</div>

如果在 TypeScript 中使用,可以加上 FunctionalComponent 類型:

js
import { type FunctionalComponent, h, mergeProps } from 'vue'

const Wrapper: FunctionalComponent = (props, { slots }) => {
  return h('div', mergeProps(props, {
    'class': 'wrapper-class',
    'data-label': 'wrapper label',
  }), slots)
}

提示

如果不想要使用傳入元件的方式的話,可以改用 <FloatContent> 元件,使用方法參考組合模式

Released under the MIT License.