传递Todo对象
1、在打开对话框时,将选中的todo
对象复制后设置为currentTodo
<el-table-column label="操作">
<template slot-scope="scope">
<el-button size="small" type="warning" icon="el-icon-edit" @click="editTodo(scope.row)"></el-button>
<el-button size="small" type="danger" icon="el-icon-delete"></el-button>
</template>
</el-table-column>
editTodo (row) {
this.currentTodo = JSON.parse(JSON.stringify(row))
this.currentAuthors = this.currentTodo.author
this.editShow = true
}
2、此时点击编辑按钮后,即可看到数据已传入
添加路由
3、在server
端新增put
方法路由用于更新数据
router.route('/:id').put((req, res) => {
Todo.findByIdAndUpdate(req.params.id, {$set:req.body}, {new: true}, (err, todo) => {
if (err) console.log(err)
res.json(todo)
})
})
异步请求
4、回到client
端,使用axios
发送更新请求
editAjax () {
this.$ajax.put('todos/' + this.currentTodo._id, this.currentTodo).then((res) => {
if (res.data) {
var index = this.data.findIndex(item => item.id === res.data._id)
this.data.splice(index, 1, res.data)
}
this.closeEditDialog()
}).catch((err) => this.$notify({
type: 'error',
message: err
}))
},
更新Todo状态
5、在操作栏中新增三个按钮
<el-table-column label="操作">
<template slot-scope="scope">
<!-- 启动学习计划 -->
<el-button v-if="scope.row.status === 0 || scope.row.status === 2" @click="updateStatusAjax(scope.row, 1)" size="small" type="primary" icon="el-icon-arrow-right"></el-button>
<!-- 搁置学习计划 -->
<el-button v-if="scope.row.status === 1" @click="updateStatusAjax(scope.row, 2)" size="small" type="info" icon="el-icon-loading"></el-button>
<!-- 完成学习计划 -->
<el-button v-if="scope.row.status === 1" @click="updateStatusAjax(scope.row, 3)" size="small" type="success" icon="el-icon-check"></el-button>
<el-button size="small" type="warning" icon="el-icon-edit" @click="editTodo(scope.row)"></el-button>
<el-button size="small" type="danger" icon="el-icon-delete"></el-button>
</template>
</el-table-column>
6、向之前写好的PUT
路由发送ajax
请求更新状态
updateStatusAjax (row, status) {
var todo = {_id: row._id, status}
this.$ajax.put('todos/' + todo._id, todo).then((res) => {
if (res.data) {
var index = this.data.findIndex(item => item._id === res.data._id)
this.data.splice(index, 1, res.data)
}
}).catch((err) => this.$notify({
type: 'error',
message: err
}))
}
7、现在就可以更新todo
的状态了
删除数据
8、与之前更新方法类似,为按钮绑定ajax
方法
<el-button size="small" type="danger" icon="el-icon-delete" @click="removeTodoAjax(scope.row)"></el-button>
removeTodoAjax (row) {
this.$confirm('确定要删除?').then(() => {
this.$ajax.delete('todos/' + row._id).then((res) => {
if (res.data) {
var index = this.data.findIndex(item => item._id === res.data._id)
this.data.splice(index, 1)
}
})
}).catch((err) => this.$notify({
type: 'error',
message: err
}))
}
9、在服务器端添加delete
方法路由
router.route('/:id').put((req, res) => {
Todo.findByIdAndUpdate(req.params.id, {$set:req.body}, {new: true}, (err, todo) => {
if (err) console.log(err)
res.json(todo)
})
}).delete((req, res) => {
Todo.findByIdAndRemove(req.params.id, (err, todo) => {
if (err) console.log(err)
res.json(todo)
})
})
10、实现删除功能
删除成功
小结
目前已实现了数据的增删改查功能,接下来将实现数据的导入导出功能