当前位置:首页 > VUE

vue实现班级随机分组

2026-01-22 18:08:51VUE

Vue实现班级随机分组的方法

准备数据

在Vue组件中定义学生列表和分组结果的数据结构。通常使用数组存储学生姓名,分组结果可以用二维数组表示。

data() {
  return {
    students: ['张三', '李四', '王五', '赵六', '钱七', '孙八', '周九', '吴十'],
    groups: []
  }
}

实现随机分组算法

创建一个方法来随机打乱学生数组并分组。使用Fisher-Yates洗牌算法实现随机排序。

vue实现班级随机分组

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>

处理特殊情况

考虑学生人数不能被组数整除的情况,可以调整最后一组人数或提示用户。

vue实现班级随机分组

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;
}

标签: 班级vue
分享给朋友:

相关文章

vue实现视频会议

vue实现视频会议

使用 Vue 实现视频会议 技术选型 Vue.js 作为前端框架,结合 WebRTC 技术实现实时音视频通信。常用的库包括: peerjs:简化 WebRTC 的点对点连接。 socket.io:用…

vue 实现菜单

vue 实现菜单

Vue 实现菜单的方法 使用 Vue 实现菜单可以通过多种方式,以下是几种常见的方法: 使用 Vue Router 实现动态路由菜单 通过 Vue Router 可以动态生成菜单,根据路由配置自动渲…

vue实现alert

vue实现alert

实现自定义 Alert 组件 在 Vue 中可以通过组件化方式实现自定义 Alert 弹窗。以下是基于 Vue 3 的实现示例: 组件代码 (Alert.vue) <template&g…

vue实现tablegrid

vue实现tablegrid

Vue 实现 TableGrid 的方法 使用 Element UI 的 Table 组件 Element UI 提供了强大的 Table 组件,可以快速实现表格布局。安装 Element UI 后,…

vue slot实现

vue slot实现

vue slot 的实现方法 在 Vue 中,slot 是一种内容分发机制,允许父组件向子组件传递模板内容。以下是几种常见的 slot 实现方式: 默认 slot 默认 slot 是最基础的 sl…

vue实现画图

vue实现画图

Vue 实现画图功能 在 Vue 中实现画图功能通常需要结合 HTML5 的 <canvas> 元素或第三方库。以下是几种常见的方法: 使用原生 Canvas API 通过 Vue 直…