vue实现班级随机分组
实现思路
使用 Vue 实现班级随机分组,可以通过以下步骤完成。假设班级成员数据存储在数组中,随机分组算法将打乱数组顺序并按照指定每组人数进行分割。
数据准备
定义一个数组存储班级成员信息,每个成员可以是字符串或对象形式。例如:

data() {
return {
students: ['张三', '李四', '王五', '赵六', '钱七', '孙八', '周九', '吴十'],
groupSize: 2,
groups: []
}
}
随机分组方法
编写一个方法实现随机分组逻辑。使用 Fisher-Yates 算法打乱数组顺序,然后按照指定组大小分割数组。
methods: {
shuffleArray(array) {
const shuffled = [...array];
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
return shuffled;
},
randomizeGroups() {
const shuffled = this.shuffleArray(this.students);
this.groups = [];
for (let i = 0; i < shuffled.length; i += this.groupSize) {
this.groups.push(shuffled.slice(i, i + this.groupSize));
}
}
}
模板展示
在模板中展示分组结果,可以使用 v-for 循环渲染各组及其成员。

<template>
<div>
<button @click="randomizeGroups">随机分组</button>
<div v-for="(group, index) in groups" :key="index">
<h3>第 {{ index + 1 }} 组</h3>
<ul>
<li v-for="(student, studentIndex) in group" :key="studentIndex">
{{ student }}
</li>
</ul>
</div>
</div>
</template>
完整组件代码
将以上部分组合成一个完整的 Vue 组件。
<template>
<div>
<button @click="randomizeGroups">随机分组</button>
<div v-for="(group, index) in groups" :key="index">
<h3>第 {{ index + 1 }} 组</h3>
<ul>
<li v-for="(student, studentIndex) in group" :key="studentIndex">
{{ student }}
</li>
</ul>
</div>
</div>
</template>
<script>
export default {
data() {
return {
students: ['张三', '李四', '王五', '赵六', '钱七', '孙八', '周九', '吴十'],
groupSize: 2,
groups: []
}
},
methods: {
shuffleArray(array) {
const shuffled = [...array];
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
return shuffled;
},
randomizeGroups() {
const shuffled = this.shuffleArray(this.students);
this.groups = [];
for (let i = 0; i < shuffled.length; i += this.groupSize) {
this.groups.push(shuffled.slice(i, i + this.groupSize));
}
}
}
}
</script>
<style scoped>
ul {
list-style-type: none;
padding: 0;
}
</style>
扩展功能
如果需要更复杂的功能,比如指定组数而非每组人数,可以调整分组逻辑。例如:
randomizeGroupsByGroupCount(groupCount) {
const shuffled = this.shuffleArray(this.students);
this.groups = Array.from({ length: groupCount }, () => []);
shuffled.forEach((student, index) => {
this.groups[index % groupCount].push(student);
});
}
调用时传入希望分成的组数即可。






