vue实现班级随机分组
Vue实现班级随机分组的方法
准备数据
在Vue组件中定义学生列表和分组结果的数据结构。通常使用数组存储学生姓名,分组结果可以用二维数组表示。
data() {
return {
students: ['张三', '李四', '王五', '赵六', '钱七', '孙八', '周九', '吴十'],
groups: []
}
}
实现随机分组算法
创建一个方法来随机打乱学生数组并分组。使用Fisher-Yates洗牌算法实现随机排序。
methods: {
shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array
},
randomGroup(groupSize) {
const shuffled = this.shuffleArray([...this.students])
this.groups = []
for (let i = 0; i < shuffled.length; i += groupSize) {
this.groups.push(shuffled.slice(i, i + groupSize))
}
}
}
模板渲染
在模板中添加分组按钮和结果显示区域。
<template>
<div>
<button @click="randomGroup(4)">随机分组(每组4人)</button>
<div v-for="(group, index) in groups" :key="index">
<h3>第{{ index + 1 }}组</h3>
<ul>
<li v-for="student in group" :key="student">{{ student }}</li>
</ul>
</div>
</div>
</template>
处理特殊情况
考虑学生人数不能被组数整除的情况,可以调整最后一组人数或提示用户。
randomGroup(groupSize) {
if (groupSize <= 0 || groupSize > this.students.length) {
alert('无效的组大小')
return
}
const shuffled = this.shuffleArray([...this.students])
this.groups = []
for (let i = 0; i < shuffled.length; i += groupSize) {
this.groups.push(shuffled.slice(i, i + groupSize))
}
if (this.groups.length > 1 && this.groups[this.groups.length - 1].length < groupSize) {
console.log('最后一组人数不足')
}
}
添加更多功能
可以扩展功能,如指定组数而不是每组人数,或保存分组历史。
randomGroupByGroupCount(groupCount) {
if (groupCount <= 0 || groupCount > this.students.length) {
alert('无效的组数')
return
}
const shuffled = this.shuffleArray([...this.students])
this.groups = Array.from({length: groupCount}, () => [])
shuffled.forEach((student, index) => {
this.groups[index % groupCount].push(student)
})
}
样式优化
添加CSS美化分组显示效果。
.group {
margin: 20px;
padding: 15px;
border: 1px solid #ddd;
border-radius: 5px;
}
button {
padding: 8px 16px;
background-color: #42b983;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}






