vue实现上移下移插件
实现思路
在Vue中实现上移下移功能,可以通过操作数组元素的顺序来完成。通常需要绑定点击事件,利用数组的splice方法交换元素位置。
基础实现代码
<template>
<div>
<ul>
<li v-for="(item, index) in list" :key="item.id">
{{ item.name }}
<button @click="moveUp(index)" :disabled="index === 0">上移</button>
<button @click="moveDown(index)" :disabled="index === list.length - 1">下移</button>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
list: [
{ id: 1, name: '项目1' },
{ id: 2, name: '项目2' },
{ id: 3, name: '项目3' },
{ id: 4, name: '项目4' }
]
}
},
methods: {
moveUp(index) {
if (index > 0) {
const temp = this.list[index - 1]
this.$set(this.list, index - 1, this.list[index])
this.$set(this.list, index, temp)
}
},
moveDown(index) {
if (index < this.list.length - 1) {
const temp = this.list[index + 1]
this.$set(this.list, index + 1, this.list[index])
this.$set(this.list, index, temp)
}
}
}
}
</script>
封装为可复用组件
可以将上移下移功能封装为独立组件:

<!-- MoveableList.vue -->
<template>
<ul>
<slot :items="list" :moveUp="moveUp" :moveDown="moveDown"></slot>
</ul>
</template>
<script>
export default {
props: {
value: {
type: Array,
required: true
}
},
data() {
return {
list: this.value
}
},
watch: {
value(newVal) {
this.list = newVal
},
list(newVal) {
this.$emit('input', newVal)
}
},
methods: {
moveUp(index) {
if (index > 0) {
[this.list[index - 1], this.list[index]] = [this.list[index], this.list[index - 1]]
}
},
moveDown(index) {
if (index < this.list.length - 1) {
[this.list[index], this.list[index + 1]] = [this.list[index + 1], this.list[index]]
}
}
}
}
</script>
使用封装组件
<template>
<moveable-list v-model="items">
<template v-slot="{ items, moveUp, moveDown }">
<li v-for="(item, index) in items" :key="item.id">
{{ item.name }}
<button @click="moveUp(index)" :disabled="index === 0">上移</button>
<button @click="moveDown(index)" :disabled="index === items.length - 1">下移</button>
</li>
</template>
</moveable-list>
</template>
<script>
import MoveableList from './MoveableList.vue'
export default {
components: {
MoveableList
},
data() {
return {
items: [
{ id: 1, name: '项目A' },
{ id: 2, name: '项目B' },
{ id: 3, name: '项目C' }
]
}
}
}
</script>
拖拽排序实现
如果需要更直观的交互,可以结合拖拽库实现:

<template>
<div>
<draggable v-model="list" handle=".handle">
<div v-for="(item, index) in list" :key="item.id">
<span class="handle">≡</span>
{{ item.name }}
</div>
</draggable>
</div>
</template>
<script>
import draggable from 'vuedraggable'
export default {
components: {
draggable
},
data() {
return {
list: [
{ id: 1, name: '项目1' },
{ id: 2, name: '项目2' },
{ id: 3, name: '项目3' }
]
}
}
}
</script>
<style>
.handle {
cursor: move;
margin-right: 10px;
}
</style>
注意事项
使用数组操作时要注意Vue的响应式限制,确保使用Vue.set或数组的变异方法来触发视图更新。
对于复杂数据结构,可能需要额外的处理来维护数据一致性。
拖拽实现需要安装vuedraggable库:npm install vuedraggable






