useSortable
useSortable
sortable のラッパー。
渡すことができるオプションの詳細については、Sortable ドキュメントの Sortable.options を参照してください。
::: warning
現在、useSortable は単一のリストに対するドラッグアンドドロップのソートのみを実装しています。
:::
インストール
npm i sortablejs@^1
使用方法
テンプレートリファレンスを使用する
<script setup lang="ts">
import { useSortable } from '@vueuse/integrations/useSortable'
import { shallowRef, useTemplateRef } from 'vue'
const el = useTemplateRef<HTMLElement>('el')
const list = shallowRef([{ id: 1, name: 'a' }, { id: 2, name: 'b' }, { id: 3, name: 'c' }])
useSortable(el, list)
</script>
<template>
<div ref="el">
<div v-for="item in list" :key="item.id">
{{ item.name }}
</div>
</div>
</template>
操作するセレクタを指定する
<script setup lang="ts">
import { useSortable } from '@vueuse/integrations/useSortable'
import { shallowRef, useTemplateRef } from 'vue'
const el = useTemplateRef<HTMLElement>('el')
const list = shallowRef([{ id: 1, name: 'a' }, { id: 2, name: 'b' }, { id: 3, name: 'c' }])
const animation = 200
const { option } = useSortable(el, list, {
handle: '.handle',
// またはオプションセット
// animation
})
// Sortable のオプションを設定および取得するために option メソッドを使用できます
option('animation', animation)
// option('animation') // 200
</script>
<template>
<div ref="el">
<div v-for="item in list" :key="item.id">
<span>{{ item.name }}</span>
<span class="handle">*</span>
</div>
</div>
</template>
セレクタを使用してルート要素を取得する
<script setup lang="ts">
import { useSortable } from '@vueuse/integrations/useSortable'
import { shallowRef } from 'vue'
const list = shallowRef([{ id: 1, name: 'a' }, { id: 2, name: 'b' }, { id: 3, name: 'c' }])
useSortable('#dv', list)
</script>
<template>
<div id="dv">
<div v-for="item in list" :key="item.id">
<span>{{ item.name }}</span>
</div>
</div>
</template>
ヒント
onUpdate を自分で処理したい場合は、onUpdate パラメータを渡すことができ、アイテムの位置を移動するための関数も公開しています。
import { moveArrayElement, useSortable } from '@vueuse/integrations/useSortable'
useSortable(el, list, {
onUpdate: (e) => {
// 何かを行う
moveArrayElement(list, e.oldIndex, e.newIndex, e)
// moveArrayElement はマイクロタスクで実行されるため、次のティックまで待つ必要があります。
nextTick(() => {
/* 何かを行う */
})
}
})
© 2019–PRESENT Anthony Fu https://github.com/antfu
※このページは Nuxt.js 公式ドキュメントの翻訳ページです。
公式ドキュメントの該当ページはこちら:
#