ElementUI之增删改及表单验证

⭐⭐本文章收录与ElementUI原创专栏:ElementUI专栏

⭐⭐ ElementUI的官网:ElementUI官网

目录

一.前言

二.使用ElementUI完成增删改

[2.1 后台代码](#2.1 后台代码)

[2.2 前端代码](#2.2 前端代码)

三.使用ElementUI完成表单验证


一.前言

本章是继上一篇的基础之上在做完善,上一篇是教大家如何使用ElementUI制作动态菜单栏以及表格的分页查询,本章就是继续上篇完成剩下的增删改功能,采用的是前后端分离,大家如果有不懂的可以点击上方的ElementUI的专栏进去查看哟~

二.使用ElementUI完成增删改

2.1 后台代码

增删改的后端代码:

  @RequestMapping("/addBook")
    @ResponseBody
    public JsonResponseBody<?> addBook(Book book){
        try {
            bookService.insert(book);
            return new JsonResponseBody<>("新增书本成功",true,0,null);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResponseBody<>("新增书本失败",false,0,null);
        }
    }

    @RequestMapping("/editBook")
    @ResponseBody
    public JsonResponseBody<?> editBook(Book book){
        try {
            bookService.updateByPrimaryKey(book);
            return new JsonResponseBody<>("编辑书本成功",true,0,null);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResponseBody<>("编辑书本失败",false,0,null);
        }
    }

    @RequestMapping("/delBook")
    @ResponseBody
    public JsonResponseBody<?> delBook(Book book){
        try {
            bookService.deleteByPrimaryKey(book.getId());
            return new JsonResponseBody<>("删除书本成功",true,0,null);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResponseBody<>("删除书本失败",false,0,null);
        }
    }

    @RequestMapping("/queryBookPager")
    @ResponseBody
    public JsonResponseBody<List<Book>> queryBookPager(Book book, HttpServletRequest req){
        try {
            PageBean pageBean=new PageBean();
            pageBean.setRequest(req);
            List<Book> books = bookService.queryBookPager(book, pageBean);
            return new JsonResponseBody<>("OK",true,pageBean.getTotal(),books);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResponseBody<>("分页查询书本失败",false,0,null);
        }
    }

2.2 前端代码

定义接口:

数据样式格式:都是去ElementUI官网copy的,然后根据自己的情况进行修改即可

<template>
  <div class="books" style="padding: 20px;">
    <!-- 1.搜索框 -->
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="书籍名称">
        <el-input v-model="bookname" placeholder="书籍名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
        <el-button type="primary" @click="open">新增</el-button>
      </el-form-item>
    </el-form>
    <!-- 2.表格 -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="id" label="书籍ID" width="180">
      </el-table-column>
      <el-table-column prop="bookname" label="书籍名称" width="180">
      </el-table-column>
      <el-table-column prop="price" label="书籍价格" width="180">
      </el-table-column>
      <el-table-column prop="booktype" label="书籍类型" width="180">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="open(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="del(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 3.分页条 -->
    <div class="block">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page"
        :page-sizes="[10, 20, 30, 40]" :page-size="100" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <!-- 4.多功能弹出框 -->
    <el-dialog :title='title' :visible.sync="dialogFormVisible" @close="clear">
      <el-form :model="book">
        <el-form-item label="书籍ID" :label-width="formLabelWidth">
          <el-input v-model="book.id" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="书籍名称" :label-width="formLabelWidth">
          <el-input v-model="book.bookname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="书籍价格" :label-width="formLabelWidth">
          <el-input v-model="book.price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="书籍类别" :label-width="formLabelWidth">
          <el-select v-model="book.booktype" placeholder="请选择书籍类型">
            <el-option v-for="t in types" :label="t.name" :value="t.name" :key="'key_'+t.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dosub">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

逻辑代码:新增和修改是共用一个弹框,然后用 if 判断,改变窗口的标题,接着根据窗体的标题来判断调用新增的方法还是修改的方法,删除的弹框的话也是在ElementUI官网中找的,获取id进行删除整条数据。

<script>
  export default {
    data() {
      return {
        bookname: '',
        tableData: [],
        rows: 10,
        page: 1,
        total: 0,
        title: '新增界面',
        // 默认不展示窗口
        dialogFormVisible: false,
        formLabelWidth: "100px", //宽度
        types: [],
        book: {
          id: "",
          bookname: "",
          price: "",
          booktype: ""
        }
      }
    },
    methods: {
      //删除
      del(row) {
        this.$confirm('你确定要删除该数据嘛~亲?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let url = this.axios.urls.BOOK_DEL;
          this.axios.post(url, {id:row.id}).then(r => {
            console.info(r);
            //弹出框
            this.$message({
              type: 'success',
              message: '删除成功!'
            });

            this.query({});
          }).catch(e => {})

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      dosub() {
        //新增
        //路由
        let url = this.axios.urls.BOOK_ADD;
        if (this.title == '编辑界面') {
          url = this.axios.urls.BOOK_UPD;
        }
        let params = {
          id: this.book.id,
          bookname: this.book.bookname,
          price: this.book.price,
          booktype: this.book.booktype
        };
        console.info(params);
        this.axios.post(url, params).then(r => {
          console.info(r);
          this.clear();
          this.query({});
        }).catch(e => {

        })
      },
      clear() {
        //初始化窗体
        this.dialogFormVisible = false;
        this.title = '新增界面';
        this.book = {
          id: "",
          bookname: "",
          pric: "",
          booktype: ""
        }
      },
      open(row) {
        //打开窗口
        this.dialogFormVisible = true;
        if (row) {
          this.title = '编辑界面';
          //赋值
          this.book.id = row.id;
          this.book.bookname = row.bookname;
          this.book.price = row.price;
          this.book.booktype = row.booktype;

        }
      },
      query(params) {
        //路由
        let url = this.axios.urls.BOOK_LIST;
        this.axios.get(url, {
          params: params
        }).then(r => {
          console.info(r);
          this.tableData = r.data.rows;
          this.total = r.data.total;
        }).catch(e => {

        })
      },
      onSubmit() {
        //模糊查询的字段
        let params = {
          bookname: this.bookname
        }
        this.query(params);
      },
      handleSizeChange(r) {
        // 当页大小发生变化

        let params = {
          bookname: this.bookname,
          rows: r,
          page: this.page
        }
        this.query(params);
      },
      handleCurrentChange(p) {
        // 当前页码发生变化
        let params = {
          bookname: this.bookname,
          rows: this.rows,
          page: p
        }
        this.query(params);
      }

    },
    created() {
      this.query({});
      //需要发ajax请求后台数据,在这里我给它定死了
      this.types = [{
        id: 1,
        name: '短文'
      }, {
        id: 2,
        name: '爱情'
      }, {
        id: 3,
        name: '爽文'
      }]
    }
  }
</script>

看一下效果吧:

三.使用ElementUI完成表单验证

第一步:去ElementUI官网搜索表单验证:会发现需要添加:

第二步:指定需要验证的属性字段,添加:

第三步,写验证规则

rules: {
          bookname: [{
            required: true,
            message: '请输入书籍名称',
            trigger: 'blur'
          }],
          price: [{
            required: true,
            message: '请输入书籍价格',
            trigger: 'blur'
          }],
          booktype: [{
            required: true,
            message: '请输入书籍类型',
            trigger: 'blur'
          }]
        }

最后一步使用验证规则:

代码:

 dosub() {
        // 验证表单
        this.$refs['book'].validate((valid) => {
          if (valid) {
            //新增
            //路由
            let url = this.axios.urls.BOOK_ADD;
            if (this.title == '编辑界面') {
              url = this.axios.urls.BOOK_UPD;
            }
            let params = {
              id: this.book.id,
              bookname: this.book.bookname,
              price: this.book.price,
              booktype: this.book.booktype
            };
            console.info(params);
            this.axios.post(url, params).then(r => {
              console.info(r);
              this.clear();
              this.query({});
            }).catch(e => {

            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });


      }

好啦,看看效果吧!!

相关推荐
熊的猫9 分钟前
webpack 核心模块 — loader & plugins
前端·javascript·chrome·webpack·前端框架·node.js·ecmascript
速盾cdn16 分钟前
速盾:vue的cdn是干嘛的?
服务器·前端·网络
四喜花露水1 小时前
Vue 自定义icon组件封装SVG图标
前端·javascript·vue.js
前端Hardy1 小时前
HTML&CSS: 实现可爱的冰墩墩
前端·javascript·css·html·css3
web Rookie1 小时前
JS类型检测大全:从零基础到高级应用
开发语言·前端·javascript
Au_ust2 小时前
css:基础
前端·css
帅帅哥的兜兜2 小时前
css基础:底部固定,导航栏浮动在顶部
前端·css·css3
工业甲酰苯胺2 小时前
C# 单例模式的多种实现
javascript·单例模式·c#
yi碗汤园2 小时前
【一文了解】C#基础-集合
开发语言·前端·unity·c#
就是个名称2 小时前
购物车-多元素组合动画css
前端·css