// 引入 Vue 和 Sortable.js
import Vue from 'vue';
import Sortable from 'sortablejs';
new Vue({
el: '#app',
data: {
items: ['Item 1', 'Item 2', 'Item 3', 'Item 4']
},
mounted() {
// 初始化 Sortable
const el = document.getElementById('items-list');
new Sortable(el, {
animation: 150,
onEnd: this.onEnd
});
},
methods: {
onEnd(event) {
// 更新数据以反映新的顺序
const oldIndex = event.oldIndex;
const newIndex = event.newIndex;
const movedItem = this.items.splice(oldIndex, 1)[0];
this.items.splice(newIndex, 0, movedItem);
}
}
});
<!-- HTML 部分 -->
<div id="app">
<ul id="items-list">
<li v-for="(item, index) in items" :key="index">{{ item }}</li>
</ul>
</div>
引入依赖:
import 语句引入了 Vue 和 Sortable。Vue 实例:
#app。data 中定义了一个数组 items,用于存储列表项。初始化 Sortable:
mounted 生命周期钩子中,获取到包含列表项的 DOM 元素 #items-list,并使用 new Sortable() 方法初始化 Sortable。animation 参数设置了拖拽时的动画效果。onEnd 回调函数会在拖拽结束时触发,并调用 Vue 实例中的 onEnd 方法。事件处理:
onEnd 方法接收一个 event 对象,包含了拖拽前后的索引信息 (oldIndex 和 newIndex)。splice 方法更新 items 数组,确保 Vue 的响应式机制能够正确反映新的顺序。HTML 结构:
v-for 指令遍历 items 数组,生成列表项 <li>。上一篇:vue截取字符串
下一篇:vue carousel
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站