Vue-Element UI 增删改查(值得学习,真的很详细哦)
2021-08-19 本文已影响0人
HeloWxl
公司最近在组织培训Springboot+Vue前后端分离,可特么终于要换了
简单介绍一下所涉及的技术内容
前端
- vue:^2.5.2
- vue-router:^3.0.1
- axios:^0.21.1
- element-ui:^2.15.3
后端
- spring-boot:2.1.1.RELEASE
- jdk:1.8
- mybatis-plus:3.1.1
- mysql:5.1.47
- swagger2:2.9.2
先看下效果图
后端接口
接口文档
http://localhost:8089//swagger-ui.html#/
查询
- 请求
URL | http://localhost:8089/sysUser/selectAll |
---|---|
hethod | get |
- 入参
name | 用户名 |
---|---|
current | 当前页数 |
size | 当前页数量 |
- 出参
{
"code": 0,
"data": {
"records": [
{
"id": 35,
"name": "12333",
"nickName": "33333",
"email": "132@qq.com",
"mobile": "15606981928",
"createTime": "2021-08-19 13:29:33"
}
],
"total": 13,
"size": 10,
"current": 1,
"searchCount": true,
"pages": 2
},
"msg": "执行成功"
}
新增
- 请求
URL | http://localhost:8089/sysUser/insert |
---|---|
hethod | post |
- 入参
name | 用户名 |
---|---|
nickName | 昵称 |
mobile | 手机号码 |
邮箱 |
- 出参
{
"code": 0,
"data": true,
"msg": "执行成功"
}
修改
- 请求
URL | http://localhost:8089/sysUser/update |
---|---|
hethod | post |
- 入参
name | 用户名 |
---|---|
nickName | 昵称 |
mobile | 手机号码 |
邮箱 | |
id | 主键 |
- 出参
{
"code": 0,
"data": true,
"msg": "执行成功"
}
删除
- 请求
URL | http://localhost:8089/sysUser/delete |
---|---|
hethod | post |
- 入参
idList | id集合 |
---|
- 出参
{
"code": 0,
"data": true,
"msg": "执行成功"
}
前端部分
下面内容分为以下几个部分
- 显示列表
- 查询
- 分页
- 新增
- 修改
- 删除
- 出现的问题以及解决办法
显示列表
image-20210819112356820.png- 页面代码
<template>
<el-row>
<el-col :span="24">
<el-card class="box-card">
<el-row :gutter="20" style="margin-bottom: 15px">
<el-col :span="6">
<el-input placeholder="请输入用户名" v-model="query.name" clearable>
<el-button slot="append" icon="el-icon-search"></el-button>
</el-input>
</el-col>
</el-row>
<el-table
:data="userList"
border
stripe
ref="userTable"
style="width: 100%">
<el-table-column
type="selection"
width="55">
</el-table-column>
<el-table-column
prop="name"
label="用户名"
align="center"
>
</el-table-column>
<el-table-column
prop="nickName"
label="昵称"
align="center"
>
</el-table-column>
<el-table-column
prop="email"
label="邮箱"
align="center"
>
</el-table-column>
<el-table-column
prop="mobile"
label="手机号"
align="center"
>
</el-table-column>
<el-table-column
prop="createTime"
label="创建时间"
align="center"
>
</el-table-column>
</el-table>
</el-card>
</el-col>
</el-row>
</template>
<script>
export default {
name: "SysUser",
data() {
return {
query: {
current: 1,
size: 10,
name: ''
},
userList: []
}
},
methods:{
async getUserList() {
this.$http.get('/sysUser/selectAll', {
params: this.query
}).then(res => {
if (res.data.data.records.length > 0 ){
this.userList = res.data.data.records;
}
}).catch(err => {
console.log(err);
})
}
},
created() {
this.getUserList()
}
}
</script>
<style scoped>
</style>
查询
给查询按钮绑定事件
<el-input placeholder="请输入用户名" v-model="query.name" clearable>
<el-button slot="append" icon="el-icon-search" @click="queryBtn"></el-button>
</el-input>
事件内容
queryBtn(){
// 再次调用加载用户数据方法
this.getUserList();
}
分页
image-20210819114223855.png- 新增页面内容
<el-pagination
@size-change="handleSizeChange" //每页数量大小改变事件
@current-change="handleCurrentChange" // 页数改变事件
:current-page="query.current" // 当前页数
:page-sizes="[10, 20, 30, 40, 50]"
:page-size="query.size" // 每页显示条数
layout="total, sizes, prev, pager, next, jumper"
:total="total"> // 总条数
</el-pagination>
- javascript修改
- 新增total属性,并在加载数据时进行赋值
- 新增handleSizeChange、handleCurrentChange
此时需要修改加载用户数据方法,将查询出的总页数进行赋值
// 加载用户数据
async getUserList() {
this.$http.get('/sysUser/selectAll', {
params: this.query
}).then(res => {
if (res.data.data.records.length > 0) {
this.userList = res.data.data.records;
this.total = res.data.data.total
}
}).catch(err => {
console.log(err);
})
},
//当前每页数量改变事件
handleSizeChange(newSize) {
this.query.size = newSize;
this.getUserList();
},
// 当前页数改变事件
handleCurrentChange(current) {
this.query.current = current;
this.getUserList();
}
修改页面数据
image-20210819114955161.png新增
image-20210819115824854.png-
新增弹窗页面
<!--新增弹窗--> <el-dialog center //居中 title="新增" //标题 :visible.sync="addDialogVisible" // 控制是否显示 width="30%" // 宽度 > <el-form :model="addUserForm" ref="addRuleForm" label-width="90px"> <el-form-item label="用户名"> <el-input v-model="addUserForm.name"></el-input> </el-form-item> <el-form-item label="昵称"> <el-input v-model="addUserForm.nickName"></el-input> </el-form-item> <el-form-item label="手机号码"> <el-input v-model="addUserForm.mobile"></el-input> </el-form-item> <el-form-item label="邮箱"> <el-input v-model="addUserForm.email"></el-input> </el-form-item> </el-form> <span slot="footer" class="dialog-footer"> <el-button @click="addDialogVisible = false">取 消</el-button> <el-button type="primary">确 定</el-button> </span> </el-dialog>
-
新增按钮新增点击事件,点击按钮弹出
<el-button type="primary" icon="el-icon-plus"@click="addDialogVisible=true">新增</el-button>
-
新增属性
addDialogVisible: false, addUserForm: { name: '', nickName: '', email: '', mobile: '' }
数据校验
image-20210819121104955.png- <el-form> 新增 :rules="addRules" <el-form-item> 新增prop属性 。比如用户名 prop = "name" prop = "nickName" 等等
配置检验规则
---------------------以下为自定义校验规则,return外面----------------------------
// 手机校验
let validatorPhone = function (rule, value, callback) {
if (value === '') {
callback(new Error('手机号不能为空'))
} else if (!/^1\d{10}$/.test(value)) {
callback(new Error('手机号格式错误'))
} else {
callback()
}
};
let validatorEmail = function (rule, value, callback) {
const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
if (value === '') {
callback(new Error('邮箱不能为空'))
} else if (!mailReg.test(value)) {
callback(new Error('邮箱格式错误'))
} else {
callback()
}
};
---------------------------------以下为return里面-----------------------------
addRules: {
name: [
{required: true, message: '请输入用户名', trigger: 'blur'},
{min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur'}
],
nickName: [
{required: true, message: '请输入昵称', trigger: 'blur'},
{min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur'}
],
mobile: [
{required: true, message: '请输入手机号码', trigger: 'blur'},
{validator: validatorPhone, trigger: 'blur'}
],
email: [
{required: true, message: '请输入邮箱', trigger: 'blur'},
{validator: validatorEmail, trigger: 'blur'}
]
}
-
确 定按钮绑定事件
<el-button type="primary" @click="insertSubmit">确 定</el-button>
// 新增提交 insertSubmit(){ // 判断是否通过校验 this.$refs['addRuleForm'].validate((valid) => { if (valid) { const headers = {"content-type": "application/json;charset=UTF-8"}; this.$http.post('/sysUser/insert', JSON.stringify(this.addUserForm),{headers:headers}).then(res => { if (res.data.code == 0 || res.data.data == true) { this.$message({ type: 'success', message: '保存成功!' }); this.addDialogVisible = false; this.getUserList(); } else { this.$message({ type: 'error', message: '保存失败!' }); } }).catch(err => { console.log(err); }) } else { return false; } }); }
修改
image-20210819130142801.png修改的校验采用新增一致即可!
<!--修改弹窗-->
<el-dialog
center
title="修改"
:visible.sync="updateDialogVisible"
width="30%"
>
<el-form :model="updateUserForm" ref="updateRuleForm" :rules="addRules" label-width="90px">
<el-form-item label="用户名" prop="name">
<el-input v-model="updateUserForm.name"></el-input>
</el-form-item>
<el-form-item label="昵称" prop="nickName">
<el-input v-model="updateUserForm.nickName"></el-input>
</el-form-item>
<el-form-item label="手机号码" prop="mobile">
<el-input v-model="updateUserForm.mobile"></el-input>
</el-form-item>
<el-form-item label="邮箱" prop="email">
<el-input v-model="updateUserForm.email"></el-input>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button @click="updateDialogVisible = false">取 消</el-button>
<el-button type="primary" @click="insertSubmit">确 定</el-button>
</span>
</el-dialog>
新增属性
updateDialogVisible:false,
updateUserForm: {
name: '',
nickName: '',
email: '',
mobile: '',
id:''
}
为修改按钮绑定事件
<el-button type="warning" icon="el-icon-edit" @click="updateBtn">编辑</el-button>
// 修改
updateBtn(){
// 判断是否勾选了 ,无勾选不予弹窗,并给予提示
// userTable 为table 的ref
const _selectData = this.$refs.userTable.selection;
if (_selectData.length === 0) {
this.$message({
message: '请选择一行数据',
type: 'warning'
});
return false;
} else if (_selectData.length > 1) {
this.$message({
message: '只能选中一行数据哦',
type: 'warning'
});
return false;
}
// 显示弹窗
this.updateDialogVisible = true;
// 将选中的数据进行赋值
this.updateUserForm = _selectData[0];
}
删除
image-20210819132318016.png为删除按钮绑定点击事件
<el-button type="danger" icon="el-icon-delete" @click="deleteBatch">删除</el-button>
deleteBatch() {
const ids = [];
const _selectData = this.$refs.userTable.selection;
if (_selectData.length === 0) {
this.$message({
message: '请至少选择一行数据',
type: 'warning'
});
return false;
}
for (const i in _selectData) {
ids.push(_selectData[i].id)
}
this.$confirm('是否删除?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
const headers = {"content-type": "application/json;charset=UTF-8"};
this.$http.post('/sysUser/delete', JSON.stringify(ids),{headers:headers}).then(res => {
if (res.data.code == 0 || res.data.data == true) {
this.$message({
type: 'success',
message: '删除成功!'
});
this.addDialogVisible = false;
this.getUserList();
} else {
this.$message({
type: 'error',
message: '删除失败!'
});
}
}).catch(err => {
console.log(err);
})
}).catch(() => {
return false;
});
}
问题及解决办法
-
新增完成后,再次打开新增按钮,会出现上次数据!
解决办法:
为弹窗新增一个关闭回调事件
<el-dialog
center
title="新增"
:visible.sync="addDialogVisible"
width="30%"
@close="addFormClose"
>
</el-dialog>
<!--修改弹窗-->
<el-dialog
center
title="修改"
:visible.sync="updateDialogVisible"
width="30%"
@close="updateFormClose"
>
</el-dialog>
// 新增弹窗关闭回调事件
addFormClose(){
this.$refs.addRuleForm.resetFields();
},
// 修改弹窗关闭回调事件
updateFormClose(){
this.$refs.updateRuleForm.resetFields();
}