VUE项目实战30.实现删除用户功能
Posted 光仔December
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了VUE项目实战30.实现删除用户功能相关的知识,希望对你有一定的参考价值。
接上篇《29.实现修改用户功能》
上一篇我们完成了用户修改的功能,半篇我们来完成用户删除的功能。
一、要实现的效果
我们需要实现,点击“删除”按钮的时候,弹出一个提示对画框:
当用户点击“取消”按钮,不进行删除动作,显示“已取消删除”:
当用户点击“确定”按钮时,进行后台数据删除操作,成功后显示“删除用户成功”。
二、实现删除提醒对话框
我们需要使用ElementUI提供的MessageBox弹框组件中的“确认消息”,来实现对话框:
样例代码:
<template>
<el-button type="text" @click="open">点击打开 Message Box</el-button>
</template>
<script>
export default
methods:
open()
this.$confirm('此操作将永久删除该文件, 是否继续?', '提示',
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
).then(() =>
this.$message(
type: 'success',
message: '删除成功!'
);
).catch(() =>
this.$message(
type: 'info',
message: '已取消删除'
);
);
</script>
其中“this.$confirm”就是用来弹出确认对话框的(这里需要先为VUE的原型对象挂载confirm函数),通过“.then”来指定确认之后的操作,通过“.catch”来指定用户取消之后的操作。下面我们先为组件绑定confirm函数,我们在plugins/element.js下,引用“MessageBox”组件:
import Vue from 'vue'
//篇幅原因,import中的其他项省略...
import MessageBox from 'element-ui'
//中间代码省略...
Vue.prototype.$confirm = MessageBox.confirm
上面引用了MessageBox组件后,不像其他的需要use,而是将MessageBox的confirm函数挂载给vue原型中的$confirm。这样在所有模板中就可以使用$confirm函数弹出确认对话框了。
我们在Users.vue组件中,找到删除按钮标签,然后添加click时间,并指定一个名为“removeUserById”的删除函数:
<el-tooltip effect="dark" content="删除" placement="top">
<el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)"></el-button>
</el-tooltip>
在函数中我们通过作用域插槽的scope数据对象,获取用户的id,作为参数传递至“removeUserById”方法。
在方法区域编写该方法,先给它一个确认对话框:
//根据ID删除对应用户信息
removeUserById(id)
//弹框询问用户是否删除数据
this.$confirm('此操作将永久删除用户, 是否继续?', '提示',
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
).then(() =>
this.$message(type: 'success',message: '删除成功!');
).catch(() =>
this.$message(type: 'info',message: '已取消删除' );
);
测试一下效果:
取消和确认的效果都是正常的,对话框实现完毕。
三、发起删除的逻辑请求
我们在用户点击确认的时候,发起用户在后台数据库的删除操作。
相关的接口API如下:
我们只需要传递要删除的用户ID即可。下面我们在刚刚的confirm对话框的“.then”中添加删除用户的网络请求:
//根据ID删除对应用户信息
removeUserById(id)
//弹框询问用户是否删除数据
this.$confirm('此操作将永久删除用户, 是否继续?', '提示',
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
).then(async () =>
const data: res = await this.$http.delete('users/'+id);
if(res.meta.status!==200)
return this.$message.error('删除用户失败!');
this.$message(type: 'success',message: '删除用户成功!');
//重新获取用户列表数据
this.getUsersList();
).catch(() =>
this.$message(type: 'info',message: '已取消删除' );
);
测试:
可以看到数据已经成功删除。
至此,我们的用户删除功能全部完成。
下一篇我们来正式进行权限管理开发。
参考:黑马程序员(www.itheima.com)Vue项目实战教学视频
转载请注明出处:https://blog.csdn.net/u013517797/article/details/122379795
以上是关于VUE项目实战30.实现删除用户功能的主要内容,如果未能解决你的问题,请参考以下文章