ElementUI之CUD+表单验证

简介: ElementUI之CUD+表单验证

76896d430d554fe795fdfe74e12272d0.jpg



一.ELementUI之CUD

后端CUD编写

@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    private IBookService bookService;
    @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);
        }
    }
    @RequestMapping("/queryBookCharts")
    @ResponseBody
    public JsonResponseBody<?> queryBookCharts(){
        try{
            Map<String, Object> charts = bookService.queryBookCharts();
            return new JsonResponseBody<>("OK",true,0,charts);
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResponseBody<>("查询统计分析数据失败",false,0,null);
        }
    }
    @RequestMapping("/upload")
    @ResponseBody
    public JsonResponseBody<?> upload(BookFileVo bookFileVo){
        try {
            MultipartFile bookFile = bookFileVo.getBookFile();
            System.out.println(bookFileVo);
            System.out.println(bookFile.getContentType());
            System.out.println(bookFile.getOriginalFilename());
            return new JsonResponseBody<>("上传成功",true,0,null);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResponseBody<>("上传失败",false,0,null);
        }
    }
    @RequestMapping("/download")
    public void download(HttpServletRequest request, HttpServletResponse response){
        try {
            String relativePath = "uploads/1.jpg";
            String absolutePath = request.getRealPath(relativePath);
            InputStream is = new FileInputStream(new File(absolutePath));
            OutputStream out = response.getOutputStream();
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("1.jpg", "UTF-8"));
            byte[] by = new byte[1024];
            int len = -1;
            while (-1 != (len = is.read(by))) {
                out.write(by);
            }
            is.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @RequestMapping("/downloadUrl")
    public void downloadUrl(HttpServletRequest request, HttpServletResponse response){
        String relativePath = "uploads/1.jpg";
        String absolutePath = request.getRealPath(relativePath);
        InputStream is = null;
        OutputStream out = null;
        try {
            is = new FileInputStream(new File(absolutePath));
            // 设置Content-Disposition
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode("1.jpg", "UTF-8"));
            out = response.getOutputStream();
            IOUtils.copy(is, out);
            response.flushBuffer();
            System.out.println("完成");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(out);
        }
    }
}



前端编写

配置访问路径:

在项目中的src文件下api中找到action.js进行配置数据访问的地址:

  'BOOKMSG_BOOKINFO_REQ': '/book/queryBookPager', //获取书本信息
  'BOOK_ADD': '/book/addBook',  //新增书本
  'BOOK_EDIT': '/book/editBook',  //修改书本
  'BOOK_DEL': '/book/delBook', //删除书本


弹出框窗口编写

<template>
  <div class="Book" style="padding: 30px;">
    <!-- 输入框搜索 -->
    <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="warning" @click="onSubmit()">查询</el-button>
        <el-button type="warning" icon="el-icon-plus" @click="addBook()">新增</el-button>
      </el-form-item>
    </el-form>
    <!-- 书籍的书籍表格 -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="id" label="书籍ID"></el-table-column>
      <el-table-column prop="bookname" label="书籍名称"></el-table-column>
      <el-table-column prop="price" label="书籍价格"></el-table-column>
      <el-table-column prop="booktype" label="书籍类型"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="block" style="padding: 20px;">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page"
        background :page-sizes="[10, 20, 30, 40]" :page-size="rows" layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
    <el-dialog :title="dialogName" :visible.sync="dialogFormVisible" @close="closeBookForm" width="500px">
      <el-form :model="bookForm">
        <el-form-item v-show="optiontype == 'update'" label="编号" :label-width="formLabelWidth">
          <el-input v-model="bookForm.id" autocomplete="off" :style="{width: formEleWidth}"></el-input>
        </el-form-item>
        <el-form-item label="书名" :label-width="formLabelWidth">
          <el-input v-model="bookForm.bookname" autocomplete="off" :style="{width: formEleWidth}"></el-input>
        </el-form-item>
        <el-form-item label="价格" :label-width="formLabelWidth">
          <el-input v-model="bookForm.price" autocomplete="off" :style="{width: formEleWidth}"></el-input>
        </el-form-item>
        <el-form-item label="类型" :label-width="formLabelWidth">
          <el-select v-model="bookForm.booktype" placeholder="选择类型" :style="{width:formEleWidth}">
           <el-option label="爱情" value="爱情"></el-option>
            <el-option label="都市" value="都市"></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="saveBook()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>



增删改查实现

<script>
  export default {
    name: 'BookList',
    data() {
      return {
        bookname: '',
        tableData: [],
        rows: 10,
        total: 0,
        page: 1,
        dialogFormVisible: false,
        formLabelWidth: '40px',
        formEleWidth: '400px',
        dialogName: '新增书本',
        optiontype: 'add',
        //定义验证规则
        rules:{
          bookname: [{
              required: true,
              message: '请输入书籍名称',
              trigger: 'blur'
            },
            {
              min: 1,
              max: 10,
              message: '长度在 1 到 10 个字符',
              trigger: 'blur'
            }
          ],
          price: [{
            required: true,
            message: '请输入价格',
            trigger: 'blur'
          }],
          booktype: [{
            required: true,
            message: '请输入书籍类别',
            trigger: 'blur'
          }]
        },
        //定义表单对应的model
        bookForm: {
          id: '',
          bookname: '',
          price: null,
          booktype: ''
        }
      }
    },
    methods: {
      /* 新增书本 */
      saveBook() {
        this.$refs['bookForm'].validate((valid) => {
          if (valid) {
            var url = this.axios.urls.BOOK_ADD;
            if (this.optiontype == 'update') {
              url = this.axios.urls.BOOK_EDIT;
            }
            console.log(url)
            this.axios.post(url, this.bookForm).then(d => {
              //关闭窗口
              this.closeBookForm();
              this.dialogFormVisible = false;
              this.query({});
            }).catch();
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      //选择分页
      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);
      },
      //查询方法
      query(params) {
        let url = this.axios.urls.BOOKMSG_BOOKINFO_REQ;
        this.axios.get(url, {
          params: params
        }).then(d => {
          this.tableData = d.data.rows;
          this.total = d.data.total;
        }).catch(e => {});
      },
      onSubmit() {
        let params = {
          bookname: this.bookname
        }
        console.log(params)
        this.query(params);
        this.bookname = ''
      },
      //关闭对话框时 清空表单
      closeBookForm() {
        this.bookForm.id = null;
        this.bookForm.bookname = null;
        this.bookForm.booktype = null;
        this.bookForm.price = null;
      },
      addBook() {
        this.dialogName = '新增书本信息';
        this.dialogFormVisible = true;
        this.optiontype = 'add';
      },
      handleEdit(row) {
        this.dialogName = '编辑书本信息';
        this.dialogFormVisible = true;
        this.bookForm.id = row.id;
        this.bookForm.bookname = row.bookname;
        this.bookForm.booktype = row.booktype;
        this.bookForm.price = row.price;
        this.optiontype = 'update';
      },
      //删除书本记录
      handleDelete(row) {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var url = this.axios.urls.BOOK_DEL;
          this.axios.post(url, {
            id: row.id
          }).then(r => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.query({});
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      }
    },
    created() {
      this.query({})
    }
  }
</script>


新增演示:

修改演示:


删除演示:

二、表单验证

自定义验证规则
 //定义验证规则
        rules:{
          bookname: [{
              required: true,
              message: '请输入书籍名称',
              trigger: 'blur'
            },
            {
              min: 1,
              max: 10,
              message: '长度在 1 到 10 个字符',
              trigger: 'blur'
            }
          ],
          price: [{
            required: true,
            message: '请输入价格',
            trigger: 'blur'
          }],
          booktype: [{
            required: true,
            message: '请输入书籍类别',
            trigger: 'blur'
          }]
        },


使用规则

      /* 新增书本 */
      saveBook() {
        this.$refs['bookForm'].validate((valid) => {
          if (valid) {
            //默认新增
            var url = this.axios.urls.BOOK_ADD;
            if (this.optiontype == 'update') {
              url = this.axios.urls.BOOK_EDIT;
            }
            console.log(url)
            this.axios.post(url, this.bookForm).then(d => {
              //关闭窗口
              this.closeBookForm();
              this.dialogFormVisible = false;
              this.query({});
            }).catch();
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },



效果演示:


目录
相关文章
|
6月前
|
人工智能 前端开发 物联网
|
6月前
|
JavaScript
如何在 Vue 中进行表单验证?
如何在 Vue 中进行表单验证?
66 0
|
JavaScript 前端开发 数据库
Vue之ElementUI实现CUD(增删改)及表单验证
Vue之ElementUI实现CUD(增删改)及表单验证
117 0
|
6月前
|
JavaScript 前端开发 安全
表单处理:使用 Vue 进行表单验证和提交
【4月更文挑战第22天】Vue 提供了便捷的表单组件和验证规则,支持实时用户输入验证和错误消息显示,确保数据正确性。通过封装验证逻辑和处理异步验证,增强代码复用和安全性。同时,关注用户体验,如清晰的指示和错误反馈,防止 CSRF 攻击,实现高效、安全的表单处理。
73 1
|
11月前
ElementUI之CUD+表单验证
ElementUI之CUD+表单验证
46 0
|
前端开发 关系型数据库 API
关于一篇ElementUI之CUD+表单验证
关于一篇ElementUI之CUD+表单验证
51 0
|
JavaScript NoSQL 前端开发
ElementUI结合Vue完成主页的CUD(增删改)&表单验证
ElementUI结合Vue完成主页的CUD(增删改)&表单验证
44 0
|
存储 JavaScript 前端开发
|
JavaScript 前端开发 Java
ElementUI使用小技巧
📒 程序员小王的博客:程序员小王的博客 🎉 欢迎点赞 👍 收藏 ⭐留言 📝 😊 如有编辑错误联系作者,如果有比较好的文章欢迎分享给我,我会取其精华去其糟粕 🍅java自学的学习路线:java自学的学习路线
269 0
ElementUI使用小技巧
下一篇
无影云桌面