vue实现成绩显示
Vue 实现成绩显示功能
数据准备
在 Vue 中创建一个数组或对象来存储成绩数据,可以包含学生姓名、科目、分数等信息。例如:
data() {
return {
students: [
{ name: '张三', math: 85, english: 90, science: 78 },
{ name: '李四', math: 92, english: 88, science: 85 },
{ name: '王五', math: 78, english: 82, science: 90 }
]
}
}
模板渲染
使用 Vue 的模板语法 v-for 循环遍历成绩数据,并在表格中显示:
<table>
<thead>
<tr>
<th>姓名</th>
<th>数学</th>
<th>英语</th>
<th>科学</th>
</tr>
</thead>
<tbody>
<tr v-for="student in students" :key="student.name">
<td>{{ student.name }}</td>
<td>{{ student.math }}</td>
<td>{{ student.english }}</td>
<td>{{ student.science }}</td>
</tr>
</tbody>
</table>
计算属性
如果需要计算总分或平均分,可以使用 Vue 的计算属性:
computed: {
studentsWithTotal() {
return this.students.map(student => {
return {
...student,
total: student.math + student.english + student.science,
average: (student.math + student.english + student.science) / 3
}
})
}
}
样式优化
通过 Vue 的 :class 或 :style 动态绑定样式,例如根据分数高低显示不同颜色:
<td :style="{ color: student.math >= 90 ? 'green' : student.math >= 60 ? 'black' : 'red' }">
{{ student.math }}
</td>
组件化
如果成绩显示功能较复杂,可以将其拆分为单独的组件:
Vue.component('grade-table', {
props: ['students'],
template: `
<table>
<!-- 表格内容 -->
</table>
`
})
数据交互
通过 API 获取成绩数据,使用 axios 或 fetch:
methods: {
async fetchGrades() {
try {
const response = await axios.get('/api/grades')
this.students = response.data
} catch (error) {
console.error('获取成绩失败:', error)
}
}
},
created() {
this.fetchGrades()
}
过滤与排序
添加过滤或排序功能,例如按总分排序:
computed: {
sortedStudents() {
return [...this.students].sort((a, b) => {
const totalA = a.math + a.english + a.science
const totalB = b.math + b.english + b.science
return totalB - totalA
})
}
}
响应式更新
使用 Vue 的响应式特性,当成绩数据变化时自动更新界面:
methods: {
updateGrade(name, subject, score) {
const student = this.students.find(s => s.name === name)
if (student) {
Vue.set(student, subject, score)
}
}
}
完整示例
将以上功能整合到一个完整的 Vue 实例中:
new Vue({
el: '#app',
data() {
return {
students: []
}
},
computed: {
sortedStudents() {
return [...this.students].sort((a, b) => {
const totalA = a.math + a.english + a.science
const totalB = b.math + b.english + b.science
return totalB - totalA
})
}
},
methods: {
async fetchGrades() {
try {
const response = await axios.get('/api/grades')
this.students = response.data
} catch (error) {
console.error('获取成绩失败:', error)
}
}
},
created() {
this.fetchGrades()
}
})






