运用vue开发基础知识,实现添加学生5门科目的成绩,并计算出平均值,涉及到的姓名,班级用自己的信息,具体要求如下: 点击添加成绩,可从课程数据数组中,选择一门课添加,成绩随机生成一门成绩添加成功后,将本门课程从课程数组中删除,下次不可再选择!点击删除成绩,将本门课程重新添加至课程数字中,下次可添加该门课. 5072101 2 3 当课程数组中的课程全部添加完成后,提示,无课程添加: 5当页面中,没有成绩时,点击删除成绩提示,无成绩可删除
时间: 2023-07-31 14:10:10 浏览: 37
好的,这是一个比较简单的实现,以下是代码的基本思路:
1. 在vue中定义一个课程数据数组(courses),以及一个学生成绩对象数组(students),每个学生成绩对象包含学生姓名(name)、班级(class)、各门课程的成绩(scores)和平均分数(average)。
2. 定义一个方法(addScore),用于添加成绩。在点击添加成绩时,从课程数据数组中随机选择一门课程,并生成一个随机成绩,将成绩添加到当前学生的成绩对象中。如果课程数组中没有课程了,提示无课程可添加。
3. 定义一个方法(deleteScore),用于删除成绩。在点击删除成绩时,将当前选择的课程重新添加到课程数据数组中,并从学生成绩对象中删除该课程成绩。如果当前学生对象中没有成绩可删除,提示无成绩可删除。
4. 在页面上通过v-for指令遍历学生成绩对象数组,并使用表格展示学生姓名、班级、各门课程的成绩和平均分数等信息。
5. 在添加和删除成绩时,需要注意同步更新学生对象数组中的平均分数。
下面是完整的代码实现:
```html
<template>
<div>
<table>
<thead>
<tr>
<th>姓名</th>
<th>班级</th>
<th v-for="course in courses" :key="course">{{ course }}</th>
<th>平均分</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(student, index) in students" :key="index">
<td>{{ student.name }}</td>
<td>{{ student.class }}</td>
<td v-for="(score, courseIndex) in student.scores" :key="courseIndex">{{ score }}</td>
<td>{{ student.average }}</td>
<td>
<button @click="addScore(index)" :disabled="courses.length === 0">添加成绩</button>
<button @click="deleteScore(index)" :disabled="student.scores.length === 0">删除成绩</button>
</td>
</tr>
</tbody>
</table>
<p v-if="courses.length === 0">无课程可添加</p>
<p v-if="students.length === 0">无成绩可删除</p>
</div>
</template>
<script>
export default {
data() {
return {
courses: ["语文", "数学", "英语", "物理", "化学"],
students: [
{
name: "张三",
class: "一班",
scores: [80, 90, 85, 95, 92],
average: 88.4
},
{
name: "李四",
class: "二班",
scores: [92, 88, 75, 85, 90],
average: 86
},
{
name: "王五",
class: "三班",
scores: [85, 95, 90, 80, 88],
average: 87.6
}
]
};
},
methods: {
addScore(index) {
const courseIndex = Math.floor(Math.random() * this.courses.length);
const course = this.courses.splice(courseIndex, 1)[0];
const score = Math.floor(Math.random() * 41 + 60);
this.students[index].scores.push(score);
this.students[index].average = this.calcAverage(this.students[index].scores);
alert(`添加 ${course} 成绩:${score}`);
},
deleteScore(index) {
const student = this.students[index];
if (student.scores.length > 0) {
const course = student.scores.splice(-1, 1)[0];
this.courses.push(course);
student.average = this.calcAverage(student.scores);
alert(`删除 ${course} 成绩`);
}
},
calcAverage(scores) {
const sum = scores.reduce((total, score) => total + score, 0);
return (sum / scores.length).toFixed(1);
}
}
};
</script>
<style>
table,
th,
td {
border: 1px solid black;
border-collapse: collapse;
}
th,
td {
padding: 5px;
}
</style>
```