vue2增删改查如何实现代码
时间: 2023-08-30 22:10:34 浏览: 50
我可以提供一个简单的示例,假设你已经有了一个后端API,可以执行增删改查操作,我们可以通过Vue2来调用这些API。
首先,我们需要创建一个Vue实例,并且将数据绑定到组件上。
```html
<div id="app">
<h1>Todo App</h1>
<ul>
<li v-for="todo in todos">{{ todo.title }}</li>
</ul>
</div>
```
```javascript
new Vue({
el: '#app',
data: {
todos: []
},
mounted() {
// 在组件挂载后,从后端获取数据
axios.get('/api/todos')
.then(response => {
this.todos = response.data;
})
.catch(error => {
console.log(error);
});
}
});
```
接下来,我们可以添加一个表单来允许用户添加新的todo。
```html
<form>
<input type="text" v-model="newTodo">
<button type="submit" @click.prevent="addTodo">Add Todo</button>
</form>
```
```javascript
new Vue({
el: '#app',
data: {
todos: [],
newTodo: ''
},
methods: {
addTodo() {
// 向后端发送POST请求来创建新的todo
axios.post('/api/todos', { title: this.newTodo })
.then(response => {
this.todos.push(response.data);
this.newTodo = '';
})
.catch(error => {
console.log(error);
});
}
},
mounted() {
// 在组件挂载后,从后端获取数据
axios.get('/api/todos')
.then(response => {
this.todos = response.data;
})
.catch(error => {
console.log(error);
});
}
});
```
接下来,我们可以添加一个编辑按钮和删除按钮,让用户可以编辑和删除todo。
```html
<ul>
<li v-for="todo in todos">
{{ todo.title }}
<button @click="editTodo(todo)">Edit</button>
<button @click="deleteTodo(todo)">Delete</button>
</li>
</ul>
```
```javascript
new Vue({
el: '#app',
data: {
todos: [],
newTodo: '',
editingTodo: null
},
methods: {
addTodo() {
// 向后端发送POST请求来创建新的todo
axios.post('/api/todos', { title: this.newTodo })
.then(response => {
this.todos.push(response.data);
this.newTodo = '';
})
.catch(error => {
console.log(error);
});
},
editTodo(todo) {
// 将当前编辑的todo赋值给editingTodo,以便在表单中显示
this.editingTodo = todo;
this.newTodo = todo.title;
},
updateTodo() {
// 向后端发送PUT请求来更新编辑的todo
axios.put(`/api/todos/${this.editingTodo.id}`, { title: this.newTodo })
.then(response => {
const index = this.todos.indexOf(this.editingTodo);
this.todos.splice(index, 1, response.data);
this.newTodo = '';
this.editingTodo = null;
})
.catch(error => {
console.log(error);
});
},
deleteTodo(todo) {
// 向后端发送DELETE请求来删除todo
axios.delete(`/api/todos/${todo.id}`)
.then(response => {
const index = this.todos.indexOf(todo);
this.todos.splice(index, 1);
})
.catch(error => {
console.log(error);
});
}
},
mounted() {
// 在组件挂载后,从后端获取数据
axios.get('/api/todos')
.then(response => {
this.todos = response.data;
})
.catch(error => {
console.log(error);
});
}
});
```
这样,我们就完成了一个简单的Vue2增删改查示例。