前端vue

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

2021-08-19  本文已影响0人  HeloWxl

公司最近在组织培训Springboot+Vue前后端分离,可特么终于要换了

简单介绍一下所涉及的技术内容

前端

后端

先看下效果图

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": "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 手机号码
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
<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>

此时需要修改加载用户数据方法,将查询出的总页数进行赋值

// 加载用户数据
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

数据校验

image-20210819121104955.png

配置检验规则

---------------------以下为自定义校验规则,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'}
                 ]
 }

修改

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();
    }
上一篇下一篇

猜你喜欢

热点阅读