vue实现学生列表
实现学生列表的Vue示例
以下是一个基于Vue.js实现学生列表功能的完整示例,包含数据展示、添加和删除功能。

基础模板结构
<template>
<div class="student-list">
<h3>学生列表</h3>
<div class="input-group">
<input v-model="newStudent.name" placeholder="姓名">
<input v-model="newStudent.age" placeholder="年龄" type="number">
<button @click="addStudent">添加</button>
</div>
<ul>
<li v-for="(student, index) in students" :key="index">
{{ student.name }} - {{ student.age }}岁
<button @click="removeStudent(index)">删除</button>
</li>
</ul>
</div>
</template>
数据与逻辑实现
<script>
export default {
data() {
return {
students: [
{ name: '张三', age: 18 },
{ name: '李四', age: 19 }
],
newStudent: {
name: '',
age: null
}
}
},
methods: {
addStudent() {
if (this.newStudent.name && this.newStudent.age) {
this.students.push({...this.newStudent});
this.newStudent.name = '';
this.newStudent.age = null;
}
},
removeStudent(index) {
this.students.splice(index, 1);
}
}
}
</script>
样式优化
<style scoped>
.student-list {
max-width: 500px;
margin: 0 auto;
padding: 20px;
}
.input-group {
margin-bottom: 20px;
}
input {
margin-right: 10px;
padding: 5px;
}
button {
padding: 5px 10px;
cursor: pointer;
}
ul {
list-style: none;
padding: 0;
}
li {
padding: 8px;
border-bottom: 1px solid #eee;
display: flex;
justify-content: space-between;
}
</style>
功能扩展建议
-
添加表单验证

methods: { validateStudent() { return this.newStudent.name.trim() && this.newStudent.age > 0 } } -
使用计算属性
computed: { totalStudents() { return this.students.length } } -
添加编辑功能
data() { return { editingIndex: null, // ... } }, methods: { editStudent(index) { this.editingIndex = index this.newStudent = {...this.students[index]} }, updateStudent() { if (this.validateStudent()) { this.students.splice(this.editingIndex, 1, {...this.newStudent}) this.cancelEdit() } } }
这个实现展示了Vue的核心功能:数据绑定、列表渲染、事件处理和组件化样式。可以根据实际需求进一步扩展功能,如添加分页、筛选或与后端API交互等。






