代码实现:

HTML部分:

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>学生列表</title>
	<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
	<div id="app">
		<h1>学生列表</h1>
		<button @click="addStudent">添加学生</button>
		<table>
			<thead>
				<tr>
					<th>姓名</th>
					<th>年龄</th>
					<th>操作</th>
				</tr>
			</thead>
			<tbody>
				<tr v-for="(student, index) in students" :key="student.id">
					<td>{{ student.name }}</td>
					<td>{{ student.age }}</td>
					<td><button @click="deleteStudent(index)">删除</button></td>
				</tr>
			</tbody>
		</table>
	</div>
	<script src="main.js"></script>
</body>
</html>

Vue.js部分:

var app = new Vue({
	el: '#app',
	data: {
		students: [{
			id: 1,
			name: '张三',
			age: 18
		}, {
			id: 2,
			name: '李四',
			age: 20
		}, {
			id: 3,
			name: '王五',
			age: 22
		}]
	},
	methods: {
		addStudent: function() {
			var newStudent = {
				id: this.students.length + 1,
				name: '新学生',
				age: 18
			};
			this.students.push(newStudent);
		},
		deleteStudent: function(index) {
			this.students.splice(index, 1);
		}
	}
});

说明:

1.在HTML中引入Vue.js:

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

2.在Vue.js中定义学生列表的数据students及方法addStudent和deleteStudent;

3.在HTML中使用v-for指令循环渲染学生列表,并在循环中使用v-bind指令绑定数据,使用@click指令绑定点击事件;

4.点击添加学生按钮时,调用addStudent方法,向students数组中添加一个新学生;

5.点击删除学生按钮时,调用deleteStudent方法,从students数组中删除指定学生。


原文地址: https://www.cveoy.top/t/topic/7dS 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录