Vue-Element UI 增删改查(值得学习,真的很详细哦)

公司最近在组织培训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

先看下效果图

image.png

后端接口

接口文档

http://localhost:8089//swagger-ui.html#/

image.png

查询

  • 请求
URL http://localhost:8089/sysUser/selectAll
hethod get
  • 入参
name 用户名
current 当前页数
size 当前页数量
  • 出参
{
  "code": 0,
  "data": {
    "records": [
      {
        "id": 35,
        "name": "12333",
        "nickName": "33333",
        "email": "[email protected]",
        "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 手机号码
email 邮箱
  • 出参
{
  "code": 0,
  "data": true,
  "msg": "执行成功"
}

修改

  • 请求
URL http://localhost:8089/sysUser/update
hethod post
  • 入参
name 用户名
nickName 昵称
mobile 手机号码
email 邮箱
id 主键
  • 出参
{
  "code": 0,
  "data": true,
  "msg": "执行成功"
}

删除

  • 请求
URL http://localhost:8089/sysUser/delete
hethod post
  • 入参
idList id集合
  • 出参
{
  "code": 0,
  "data": true,
  "msg": "执行成功"
}

前端部分

下面内容分为以下几个部分

  1. 显示列表
  2. 查询
  3. 分页
  4. 新增
  5. 修改
  6. 删除
  7. 出现的问题以及解决办法

显示列表

image-20210819112356820.png
  • 页面代码




查询

给查询按钮绑定事件


  

事件内容

queryBtn(){
  // 再次调用加载用户数据方法
  this.getUserList();
 }

分页

image-20210819114223855.png
  • 新增页面内容
  // 总条数

  • 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
  • 新增弹窗页面

      
    
        
            
                
            
            
                
            
            
                
            
            
                
            
        
        
            取 消
            确 定
        
    
    
  • 新增按钮新增点击事件,点击按钮弹出

    新增
    
    
  • 新增属性

    addDialogVisible: false,
    addUserForm: {
       name: '',
       nickName: '',
       email: '',
       mobile: ''
    }
    

数据校验

image-20210819121104955.png
  • 新增 :rules="addRules" 新增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'}
                 ]
 }
  • 确 定按钮绑定事件

    确 定
    
     // 新增提交
    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

修改的校验采用新增一致即可!

 

    
        
            
        
        
            
        
        
            
        
        
            
        
    
    
        取 消
        确 定
    

新增属性

updateDialogVisible:false,
updateUserForm: {
    name: '',
    nickName: '',
    email: '',
    mobile: '',
    id:''
}

为修改按钮绑定事件

编辑
// 修改
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

为删除按钮绑定点击事件

删除
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;
                });
            }

问题及解决办法

  • 新增完成后,再次打开新增按钮,会出现上次数据!
    解决办法:
    为弹窗新增一个关闭回调事件


    
        

  // 新增弹窗关闭回调事件
addFormClose(){
    this.$refs.addRuleForm.resetFields();
},
    // 修改弹窗关闭回调事件
    updateFormClose(){
        this.$refs.updateRuleForm.resetFields();
    }

你可能感兴趣的:(Vue-Element UI 增删改查(值得学习,真的很详细哦))