sortablejs vue3使用
时间: 2024-09-25 15:01:31 浏览: 59
SortableJS是一个强大的JavaScript库,用于创建拖放排序功能。在Vue3中使用SortableJS,首先你需要安装它。你可以通过npm或yarn命令行工具添加依赖:
```bash
# npm
npm install sortablejs @vueuse/core
# yarn
yarn add sortablejs @vueuse/core
```
然后,在Vue组件中引入并使用SortableJS,可以借助`@vueuse/core`库提供的插件式API。这里是一个简单的例子:
```html
<template>
<div id="draggableItems">
<div v-for="(item, index) in items" :key="index" class="ui-element">
{{ item.name }}
<button @click="swap(index, index + 1)">Swap</button>
</div>
</div>
</template>
<script setup>
import { ref } from 'vue'
import Sortable from '@sortablejs/react'
const items = ref([{ name: 'Item 1' }, { name: 'Item 2' }, { name: 'Item 3' }])
let activeSortable = null
function swap(indexA, indexB) {
const [temp] = items.value.splice(indexA, 1)
items.value.splice(indexB, 0, temp)
}
function initSortable() {
if (!activeSortable) {
activeSortable = new Sortable('#draggableItems', {
group: '__items__', // 设置排序组名
draggable: '.ui-element',
onEnd: ({ newIndex }) => {
items.value[newIndex].order = newIndex // 如果需要保存顺序,可以在这里更新数据状态
}
})
}
}
onMounted(() => {
initSortable()
})
beforeUnmount(() => {
if (activeSortable) {
activeSortable.destroy()
activeSortable = null
}
})
</script>
<style scoped>
.ui-element {
border: 1px solid #ccc;
padding: 5px;
}
</style>
```
在这个例子中,我们创建了一个可拖动的元素列表,并在结束拖动时更新数组中的顺序。记得导入Sortble和相关的CSS样式,以及在适当的时候初始化Sortable。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)