用vue实现冒泡排序
实现思路
在Vue中实现冒泡排序,可以通过数据驱动视图的特性动态展示排序过程。核心是将排序算法与Vue的响应式数据结合,通过修改数组触发视图更新。
代码实现
<template>
<div>
<button @click="startSort">开始排序</button>
<div class="array-container">
<div
v-for="(item, index) in array"
:key="index"
class="array-item"
:style="{ height: `${item * 10}px` }"
>
{{ item }}
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
array: [5, 3, 8, 4, 2],
sorting: false
}
},
methods: {
async startSort() {
if (this.sorting) return
this.sorting = true
let arr = [...this.array]
const len = arr.length
for (let i = 0; i < len - 1; i++) {
for (let j = 0; j < len - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
// 交换元素
;[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]
// 更新Vue响应式数据
this.array = [...arr]
// 添加延迟以便观察排序过程
await new Promise(resolve => setTimeout(resolve, 500))
}
}
}
this.sorting = false
}
}
}
</script>
<style>
.array-container {
display: flex;
align-items: flex-end;
gap: 10px;
margin-top: 20px;
height: 200px;
}
.array-item {
width: 30px;
background-color: #42b983;
display: flex;
justify-content: center;
align-items: flex-end;
padding-bottom: 5px;
color: white;
transition: all 0.3s ease;
}
</style>
关键点说明
使用Vue的响应式特性,在每次数组元素交换后更新this.array,触发视图重新渲染
通过await和setTimeout实现排序动画效果,使每一步变化可见

使用解构赋值[a, b] = [b, a]简洁地实现元素交换
CSS样式使数组元素以柱状图形式展示,高度与数值成正比

优化方向
添加排序状态提示,防止重复点击
实现随机数组生成功能
增加排序速度调节选项
添加排序完成的事件通知






