Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Vue

This package provides Vue bindings for@floating-ui/dom — alibrary that provides anchor positioning for a floating elementto position it next to a given reference element.

npm install @floating-ui/vue

Usage

useFloating() is the main composable:

<script setup>import {ref} from 'vue';import {useFloating} from '@floating-ui/vue';const reference = ref(null);const floating = ref(null);const {floatingStyles} = useFloating(reference, floating);</script><template>  <buttonref="reference">Button</button>  <divref="floating" :style="floatingStyles">Tooltip</div></template>

This will position the floatingTooltip element at thebottomcenter of theButton element by default.

  • reference is the reference (or anchor) element thatis being referred to for positioning.
  • floating is the floating element that is beingpositioned relative to the reference element.
  • floatingStyles is an object of positioning styles toapply to the floating element’sstyle attribute.

Disabling transform

By default, the floating element is positioned usingtransform in thefloatingStyles object. This is themost performant way to position elements, but can be disabled:

useFloating(reference, floating, {  transform: false,});

If you’d like to retain transform styles while allowing transformanimations, create a wrapper, where the outermost node is thepositioned one, and the inner is the actual styled element.

Custom position styles

The composable returns the coordinates and positioning strategydirectly iffloatingStyles is not suitable for fullcustomization.

const {x, y, strategy} = useFloating(reference, floating);

Return value

The composablereturns all the values fromcomputePosition,plus some extras to work with Vue. This includes data about thefinal placement and middleware data which are useful whenrendering.

Options

The composable accepts all theoptions fromcomputePosition,which allows you to customize the position. Here’s an example:

import {  useFloating,  offset,  flip,  shift,} from '@floating-ui/vue';// Inside your componentuseFloating(reference, floating, {  placement: 'right',  middleware: [offset(10), flip(), shift()],});

The composable also acceptsRef options:

import {  useFloating,  offset,  flip,  shift,} from '@floating-ui/vue';// Inside your componentconst placement = ref('right');const middleware = ref([offset(10), flip(), shift()]);useFloating(reference, floating, {  placement,  middleware,});

Middleware can alter thepositioning from the basicplacement, act as visibilityoptimizers, or provide data to use.

The docs for the middleware that were passed are available here:

Anchoring

The position is only calculatedonce on render, or when thereference orfloating elements changed —for example, the floating element get mounted via conditionalrendering.

To ensure the floating element remains anchored to its referenceelement in a variety of scenarios without detaching — such aswhen scrolling or resizing the page — you can pass theautoUpdate utility to thewhileElementsMounted prop:

import {useFloating, autoUpdate} from '@floating-ui/vue';// Inside your componentuseFloating(reference, floating, {  whileElementsMounted: autoUpdate,});

To pass options toautoUpdate:

useFloating(reference, floating, {  whileElementsMounted(...args) {    const cleanup = autoUpdate(...args, {animationFrame: true});    // Important! Always return the cleanup function.    return cleanup;  },});

Ensure you are using conditional rendering (v-if)for the floating element, not an opacity/visibility/displaystyle. If you are usingv-show instead, avoid thewhileElementsMounted prop.

Manual updating

WhileautoUpdate covers most cases where the position of thefloating element must be updated, it does not cover every singleone possible due to performance/platform limitations.

The composable returns anupdate() function to update theposition at will:

<script setup>const {update} = useFloating(reference, floating);</script><template>  <Panel @resize="update" /></template>

Custom components

The composable also accepts custom component template refs:

<script setup>import {ref} from 'vue';import {useFloating} from '@floating-ui/vue';import MyButtonfrom './MyButton.vue';import MyTooltipfrom './MyTooltip.vue';const reference = ref(null);const floating = ref(null);const {floatingStyles} = useFloating(reference, floating);</script><template>  <MyButton ref="reference">Button</MyButton>  <MyTooltip ref="floating">Tooltip</MyTooltip></template>

Effects

Positioning is done in an async function, which means theposition is ready during a microtask, after layout effects areexecuted. This means initially, the floating element is situatedat the top-left (0, 0) of its offset container — so calling DOMmethods that cause side-effects like scrolling will result inunexpected behavior.

The composable returns anisPositioned boolean refthat lets you know if the floating element has been positioned:

const open = ref(false);const {isPositioned} = useFloating(reference, floating, {  // Synchronize `isPositioned` with an `open` ref.  open,});// Each time the floating element opens, we want to focus and// scroll some element into view.watch(isPositioned, (isPositioned) => {  if (isPositioned) {    someElement.focus();    someElement.scrollIntoView();  }});

Theopen option accepts a boolean ref that represents theopen/close state of the floating element. This ensures you canwait each time it opens when the host component does not unmount,which is necessary in cases where the reference element relocateson the page.

Arrow

Thearrow module exported from this package allows templaterefs in addition to elements. Seearrow fordetails.

<script setup>import {arrow, useFloating} from '@floating-ui/vue';import {ref} from 'vue';const reference = ref(null);const floating = ref(null);const floatingArrow = ref(null);const {floatingStyles, middlewareData} = useFloating(  reference,  floating,  {    middleware: [arrow({element: floatingArrow})],  },);</script><template>  <spanref="reference">Reference</span>  <divref="floating" :style="floatingStyles">    Floating    <div      ref="floatingArrow"      :style="{        position: 'absolute',        left:          middlewareData.arrow?.x != null            ? `${middlewareData.arrow.x}px`            : '',        top:          middlewareData.arrow?.y != null            ? `${middlewareData.arrow.y}px`            : '',      }"    ></div>  </div></template>

Virtual Element

SeeVirtual Elements for details.Example:

<script setup>import {onMounted, ref} from 'vue';import {useFloating} from '@floating-ui/vue';const reference = ref(null);const floating = ref(null);const {floatingStyles} = useFloating(reference, floating);onMounted(() => {  /**   * Assign the virtual element to reference inside   * a lifecycle hook or effect or event handler.   */  reference.value = {    getBoundingClientRect() {      return {        // ...      };    },  };});</script><template>  <divref="floating">Tooltip</div></template>
Prev
React Native
Next
Migration

[8]ページ先頭

©2009-2025 Movatter.jp