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

先看下效果圖

後端接口

接口文檔

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": "[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. 出現的問題以及解決辦法

顯示列表

  • 頁面代碼
<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();
 }

分頁

  • 新增頁面內容
<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();
}

修改頁面數據

新增

  • 新增彈窗頁面

      <!--新增彈窗-->
    <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: ''
    }
    

數據校驗

  • <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;
            }
        });
    }
    

修改


修改的校驗採用新增一致即可!

 <!--修改彈窗-->
<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];
}

刪除

爲刪除按鈕綁定點擊事件

<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();
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章