Vue.js增删改查示例代码 - 带表格和中文注释
<!DOCTYPE html>
<html lang='zh-CN'>
<head>
<meta charset='UTF-8'>
<title>Vue.js增删改查示例</title>
<script src='https://cdn.jsdelivr.net/npm/vue/dist/vue.js'></script>
</head>
<body>
<div id='app'>
<h1>Vue.js增删改查示例</h1>
<form @submit.prevent='add'>
<label>
<span>姓名:</span>
<input type='text' v-model='newName'>
</label>
<label>
<span>年龄:</span>
<input type='number' v-model='newAge'>
</label>
<button type='submit'>添加</button>
</form>
<table>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for='(item, index) in list' :key='index'>
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
<td>
<button @click='edit(index)'>编辑</button>
<button @click='del(index)'>删除</button>
</td>
</tr>
</tbody>
</table>
<div v-if='editingIndex !== null'>
<h2>编辑</h2>
<form @submit.prevent='save'>
<label>
<span>姓名:</span>
<input type='text' v-model='list[editingIndex].name'>
</label>
<label>
<span>年龄:</span>
<input type='number' v-model='list[editingIndex].age'>
</label>
<button type='submit'>保存</button>
</form>
</div>
</div>
<script>
new Vue({
el: '#app',
data: {
newName: '',
newAge: '',
editingIndex: null,
list: [
{ name: '张三', age: 20 },
{ name: '李四', age: 22 },
{ name: '王五', age: 25 }
]
},
methods: {
add: function() { // 添加
this.list.push({
name: this.newName,
age: this.newAge
});
this.newName = '';
this.newAge = '';
},
del: function(index) { // 删除
this.list.splice(index, 1);
},
edit: function(index) { // 编辑
this.editingIndex = index;
},
save: function() { // 保存
this.editingIndex = null;
}
}
});
</script>
</body>
</html>
<!-- 本示例为Vue.js增删改查的HTML代码,包含一个表格和中文注释。 -->
<!-- 使用v-for指令实现列表渲染,v-model实现双向数据绑定,@click监听事件。 -->
<!-- 可以实现添加、删除、编辑和保存功能。 -->
原文地址: https://www.cveoy.top/t/topic/n5sm 著作权归作者所有。请勿转载和采集!