编号 | 科目 | 成绩 | 操作 | |
---|---|---|---|---|
{{ index+1 }} | {{ item.subject }} | {{ item.score }} | 删除 | |
暂无数据 | ||||
总分:{{ totalScore }} 平均分:{{ averageScore }} |
科目:
分数:
案例-成绩管理#
需求说明:
- 渲染功能
- 删除功能
- 添加功能
- 统计总分,求平均分
渲染用v-for即可,略
删除功能#
<td><a @click.prevent="del(item.id)" href="#">删除</a></td>
del(id) {
this.list = this.list.filter(item => item.id !== id);
},
添加功能#
<div class="form-item">
<div class="label">科目:</div>
<div class="input">
<input v-model.trim="subject" type="text" placeholder="请输入科目" />
</div>
</div>
<div class="form-item">
<div class="label">分数:</div>
<div class="input">
<input v-model.number="score" type="number" placeholder="请输入分数" />
</div>
</div>
<div class="form-item">
<div class="label"></div>
<div class="input">
<button @click="add" class="submit">添加</button>
</div>
</div>
add() {
if (!this.subject || !this.score) {
alert('请输入科目或成绩');
return;
}
this.list.unshift({ id: +new Date(), subject: this.subject, score: this.score });
this.clear();
},
clear() {
this.subject = '';
this.score = '';
},
总分平均分#
使用计算属性
<td colspan="5">
<span>总分:{% raw %}{{ totalScore }}{% endraw %}</span>
<span style="margin-left: 50px">平均分:{% raw %}{{ averageScore }}{% endraw %}</span>
</td>
computed: {
totalScore() {
return this.list.reduce((sum, item) => sum + item.score, 0);
},
averageScore() {
if (this.list.length === 0) {
return 0;
}
return (this.totalScore / this.list.length).toFixed(2);
},
},