vue实现随机分组功能
实现随机分组功能
在Vue中实现随机分组功能可以通过以下步骤完成。假设需要将一组人员随机分成若干小组。
数据准备 定义一个人员数组和分组数量:
data() {
return {
people: ['张三', '李四', '王五', '赵六', '钱七', '孙八', '周九', '吴十'],
groupCount: 2,
groups: []
}
}
随机排序算法 使用Fisher-Yates洗牌算法实现随机排序:
methods: {
shuffleArray(array) {
const result = [...array]
for (let i = result.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1))
;[result[i], result[j]] = [result[j], result[i]]
}
return result
}
}
分组实现 将随机排序后的人员分配到各小组:
methods: {
randomGroup() {
const shuffled = this.shuffleArray(this.people)
this.groups = Array.from({ length: this.groupCount }, () => [])
shuffled.forEach((person, index) => {
const groupIndex = index % this.groupCount
this.groups[groupIndex].push(person)
})
}
}
模板展示 在模板中显示分组结果:
<template>
<div>
<button @click="randomGroup">随机分组</button>
<div v-for="(group, index) in groups" :key="index">
<h3>第{{ index + 1 }}组</h3>
<ul>
<li v-for="person in group" :key="person">{{ person }}</li>
</ul>
</div>
</div>
</template>
进阶功能实现
控制每组人数 如果需要每组人数相同或指定人数:
methods: {
randomGroupWithSize() {
const shuffled = this.shuffleArray(this.people)
const groupSize = Math.ceil(this.people.length / this.groupCount)
this.groups = []
for (let i = 0; i < this.groupCount; i++) {
this.groups.push(shuffled.slice(i * groupSize, (i + 1) * groupSize))
}
}
}
保存分组历史 添加分组历史记录功能:
data() {
return {
history: []
}
},
methods: {
randomGroup() {
// ...原有分组代码
this.history.push([...this.groups])
}
}
注意事项
- 随机性依赖Math.random(),不适合高安全性场景
- 人员数量不足时会自动调整分组数量
- 使用v-for时需要添加合适的key
- 移动端可能需要调整UI显示方式
以上实现可以根据实际需求进行调整,如添加分组条件限制、保存分组结果等功能。







