vue实现 div兑换
Vue 实现 div 交换功能
在 Vue 中实现两个 div 元素的交换可以通过多种方法实现,以下提供两种常见方案:

方案一:通过动态绑定 v-for 和数组操作
利用 Vue 的响应式特性,通过修改数组顺序实现元素交换。

<template>
<div>
<div v-for="(item, index) in items" :key="item.id" class="swap-item">
{{ item.content }}
<button @click="swapItems(index)">交换</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, content: '元素A' },
{ id: 2, content: '元素B' }
]
}
},
methods: {
swapItems(index) {
if (index < this.items.length - 1) {
const temp = this.items[index]
this.$set(this.items, index, this.items[index + 1])
this.$set(this.items, index + 1, temp)
}
}
}
}
</script>
方案二:通过 CSS 布局和动态类名
利用 CSS 的布局特性实现视觉上的交换效果。
<template>
<div class="container">
<div
class="box"
:class="{ 'box-left': !swapped, 'box-right': swapped }"
@click="swap"
>
元素1
</div>
<div
class="box"
:class="{ 'box-right': !swapped, 'box-left': swapped }"
@click="swap"
>
元素2
</div>
</div>
</template>
<script>
export default {
data() {
return {
swapped: false
}
},
methods: {
swap() {
this.swapped = !this.swapped
}
}
}
</script>
<style>
.container {
display: flex;
justify-content: center;
}
.box {
width: 100px;
height: 100px;
margin: 10px;
cursor: pointer;
}
.box-left {
order: 1;
}
.box-right {
order: 2;
}
</style>
进阶实现:拖拽交换功能
如需实现拖拽交换效果,可以使用第三方库如 vuedraggable:
<template>
<draggable v-model="items" group="elements">
<div v-for="item in items" :key="item.id">
{{ item.content }}
</div>
</draggable>
</template>
<script>
import draggable from 'vuedraggable'
export default {
components: { draggable },
data() {
return {
items: [
{ id: 1, content: '可拖动元素A' },
{ id: 2, content: '可拖动元素B' }
]
}
}
}
</script>
以上方案可根据具体需求选择使用,方案一适用于编程式交换,方案二适合视觉交互,拖拽方案则提供最佳用户体验。






