在vue实现学生表格
实现学生表格的基本结构
在Vue中实现学生表格需要使用<table>标签结合Vue的数据绑定功能。准备一个数组存储学生数据,通过v-for指令动态渲染表格行。
<template>
<div>
<table>
<thead>
<tr>
<th>学号</th>
<th>姓名</th>
<th>年龄</th>
<th>成绩</th>
</tr>
</thead>
<tbody>
<tr v-for="student in students" :key="student.id">
<td>{{ student.id }}</td>
<td>{{ student.name }}</td>
<td>{{ student.age }}</td>
<td>{{ student.score }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
data() {
return {
students: [
{ id: 1, name: '张三', age: 18, score: 90 },
{ id: 2, name: '李四', age: 19, score: 85 },
{ id: 3, name: '王五', age: 20, score: 92 }
]
}
}
}
</script>
添加表格样式
为表格添加基础CSS样式可以提升视觉效果。使用scoped样式确保样式只作用于当前组件。
<style scoped>
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
tr:nth-child(even) {
background-color: #f9f9f9;
}
tr:hover {
background-color: #e9e9e9;
}
</style>
实现动态增删功能
通过方法控制学生数据的增删操作,添加对应的按钮和事件处理。
<template>
<div>
<button @click="addStudent">添加学生</button>
<table>
<!-- 表头省略 -->
<tbody>
<tr v-for="(student, index) in students" :key="student.id">
<!-- 单元格省略 -->
<td>
<button @click="deleteStudent(index)">删除</button>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
methods: {
addStudent() {
const newId = this.students.length + 1
this.students.push({
id: newId,
name: `新学生${newId}`,
age: 18,
score: Math.floor(Math.random() * 50) + 50
})
},
deleteStudent(index) {
this.students.splice(index, 1)
}
}
}
</script>
添加排序功能
实现按列排序功能需要添加排序方法和排序状态管理。
<template>
<div>
<table>
<thead>
<tr>
<th @click="sortBy('id')">学号</th>
<th @click="sortBy('name')">姓名</th>
<th @click="sortBy('age')">年龄</th>
<th @click="sortBy('score')">成绩</th>
</tr>
</thead>
<!-- 表格内容省略 -->
</table>
</div>
</template>
<script>
export default {
data() {
return {
sortKey: '',
sortOrder: 1
}
},
methods: {
sortBy(key) {
if (this.sortKey === key) {
this.sortOrder *= -1
} else {
this.sortKey = key
this.sortOrder = 1
}
this.students.sort((a, b) => {
if (a[key] < b[key]) return -1 * this.sortOrder
if (a[key] > b[key]) return 1 * this.sortOrder
return 0
})
}
}
}
</script>
实现分页功能
对于大量数据,添加分页功能可以提升用户体验。
<template>
<div>
<table><!-- 表格内容省略 --></table>
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span>第 {{ currentPage }} 页</span>
<button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 5
}
},
computed: {
paginatedStudents() {
const start = (this.currentPage - 1) * this.pageSize
return this.students.slice(start, start + this.pageSize)
},
totalPages() {
return Math.ceil(this.students.length / this.pageSize)
}
},
methods: {
prevPage() {
if (this.currentPage > 1) this.currentPage--
},
nextPage() {
if (this.currentPage < this.totalPages) this.currentPage++
}
}
}
</script>






