Vue.js CRUD 示例:简单易懂的增删改查实现
以下是一个基本的 Vue.js 增删改查示例:
<!DOCTYPE html>
<html>
<head>
<title>Vue.js CRUD Example</title>
<script src='https://cdn.jsdelivr.net/npm/vue/dist/vue.js'></script>
</head>
<body>
<div id='app'>
<h1>Vue.js CRUD Example</h1>
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Age</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr v-for='person in people' :key='person.id'>
<td>{{ person.id }}</td>
<td>{{ person.name }}</td>
<td>{{ person.age }}</td>
<td>
<button @click='editPerson(person)'>Edit</button>
<button @click='deletePerson(person)'>Delete</button>
</td>
</tr>
</tbody>
</table>
<form @submit.prevent='submitForm'>
<label for='name'>Name:</label>
<input type='text' id='name' v-model='person.name' required>
<label for='age'>Age:</label>
<input type='number' id='age' v-model='person.age' required>
<button type='submit' :disabled='!formIsValid'>Save</button>
</form>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
people: [
{ id: 1, name: 'John', age: 25 },
{ id: 2, name: 'Jane', age: 30 },
{ id: 3, name: 'Bob', age: 35 }
],
person: {
id: null,
name: '',
age: null
},
editing: false
},
methods: {
submitForm: function() {
if (this.editing) {
this.updatePerson();
} else {
this.addPerson();
}
this.resetForm();
},
addPerson: function() {
var id = this.people.length + 1;
this.people.push({
id: id,
name: this.person.name,
age: this.person.age
});
},
editPerson: function(person) {
this.editing = true;
this.person.id = person.id;
this.person.name = person.name;
this.person.age = person.age;
},
updatePerson: function() {
var index = this.people.findIndex(p => p.id === this.person.id);
this.people[index].name = this.person.name;
this.people[index].age = this.person.age;
},
deletePerson: function(person) {
var index = this.people.findIndex(p => p.id === person.id);
this.people.splice(index, 1);
},
resetForm: function() {
this.person.id = null;
this.person.name = '';
this.person.age = null;
this.editing = false;
}
},
computed: {
formIsValid: function() {
return this.person.name && this.person.age;
}
}
});
</script>
</body>
</html>
在这个示例中,我们有一个人物对象,包括 id、name 和 age 属性。我们还有一个 people 数组,用于存储所有人物。
我们使用 v-for 指令在表格中显示每个人物,并使用 v-model 指令将表单绑定到 person 对象。
我们还有一些方法来添加、编辑、更新和删除人物。当我们点击“保存”按钮时,我们使用 submitForm 方法来决定是添加新人物还是更新现有人物。
我们还有一个计算属性来检查表单是否有效。如果姓名和年龄都存在,表单就是有效的。
这是一个基本的 Vue.js 增删改查示例,您可以根据自己的需求进行修改和扩展。
原文地址: https://www.cveoy.top/t/topic/n5sb 著作权归作者所有。请勿转载和采集!