Vue之ElementUI实现CUD(增删改)及表单验证

简介: Vue之ElementUI实现CUD(增删改)及表单验证



前言

       上期的博客中我与大家分享了有关Vue和ElementUI实现项目左侧的动态树形菜单栏及将数据从数据库拿到在前端与数据表格进行绑定交互,而且还实现了模糊查询和分页条的功能。今天的这期博客Vue之ElementUI实现CUD(增删改)及表单验证是居于上一期博客的数据表格的基础上实现增删改及表单验证的功能,希望大家能够耐心仔细阅读完,谢谢大家的支持。

一、CUD(增删改)功能实现

1. 配置CUD(增删改)功能的接口

       在action.js文件中配置CUD(增删改)功能的请求接口方法,方便后续代码开发调用。

注意:在准备进行后续开发的时候,记得将src文件下的main.js文件中的process.env.MOCK && require('@/mock')即mockjs注释掉否则影响开发。

2. 编写新增窗体界面及完成新增功能

<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" stripe style="width: 100%">
      <el-table-column prop="id" label="书籍编号" width="180">
      </el-table-column>
      <el-table-column prop="bookname" label="书籍名称" width="180">
      </el-table-column>
      <el-table-column prop="price" label="书籍价格">
      </el-table-column>
      <el-table-column prop="booktype" label="书籍类型">
      </el-table-column>
    </el-table>
    <!-- 3.分页条 -->
    <div class="block" style="padding: 20px;">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page"
        :page-sizes="[10, 20, 30, 40]" :page-size="rows" layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
    <!-- 编辑窗体 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" @close="clear">
      <el-form :model="book">
        <el-form-item label="书籍编号" :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>
<script>
  export default {
    data() {
      return {
        bookname: '',
        tableData: [],
        rows: 10,
        page: 1,
        total: 0,
        title: '新增窗体',
        dialogFormVisible: false,
        formLabelWidth: '100px',
        book: {
          id: '',
          bookname: '',
          price: '',
          booktype: ''
        },
        types: []
      }
    },
    methods: {
      // 提交
      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
        }
        this.axios.post(url, params).then(r => {
          console.log(r);
          this.clear();//关闭
          this.query({});//刷新
        }).catch(e => {
        })
      },
      // 初始化窗体
      clear() {
        this.dialogFormVisible = false;
        this.title='新增窗体';
        this.book={
          id: '',
          bookname: '',
          price: '',
          booktype: ''
        }
      },
      open() {
        // 待开窗体
        this.dialogFormVisible = true;
      },
      // 定义一个查询的方法,方便调用减少代码冗余
      query(params) {
        // 向后台请求数据的访问路径
        let url = this.axios.urls.BookList;
        this.axios.get(url, {
          params: params
        }).then(r => {
          console.log(r);
          this.tableData = r.data.rows;
          this.total = r.data.total;
        }).catch(e => {
        })
      },
      onSubmit() {
        let params = {
          bookname: this.bookname,
        }
        // 调用查询方法
        this.query(params);
      },
      handleSizeChange(r) { //当页大小发生变化
        // 输出查看
        console.log("当前页大小:" + r);
        let params = {
          bookname: this.bookname,
          rows: r,
          page: this.page
        }
        // 调用查询方法
        this.query(params);
      },
      handleCurrentChange(p) { //当当前页页码大小发生变化
        // 输出查看
        console.log("当前页码:" + p);
        let params = {
          bookname: this.bookname,
          page: p,
          rows: this.rows
        }
        // 调用查询方法
        this.query(params);
      }
    },
    created() {
      // 调用查询方法
      this.query({});
      this.types = [{
        id: 1,
        name: '爱情'
      }, {
        id: 2,
        name: '玄幻'
      }, {
        id: 3,
        name: '激情'
      }]
    }
  }
</script>
<style>
</style>

注意事项:

       记得在提交新增请求数据后,加上 this.clear();//关闭
         this.query({});//刷新
两行代码。

效果

3. 编写编辑功能代码

添加操作栏

<el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="open(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>

编写功能js代码

<script>
  export default {
    data() {
      return {
        bookname: '',
        tableData: [],
        rows: 10,
        page: 1,
        total: 0,
        title: '新增窗体',
        dialogFormVisible: false,
        formLabelWidth: '100px',
        book: {
          id: '',
          bookname: '',
          price: '',
          booktype: ''
        },
        types: []
      }
    },
    methods: {
      // 提交
      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
        }
        this.axios.post(url, params).then(r => {
          console.log(r);
          this.clear(); //关闭
          this.query({}); //刷新
        }).catch(e => {
        })
      },
      // 初始化窗体
      clear() {
        this.dialogFormVisible = false;
        this.title = '新增窗体';
        this.book = {
          id: '',
          bookname: '',
          price: '',
          booktype: ''
        }
      },
      open(idx, 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.BookList;
        this.axios.get(url, {
          params: params
        }).then(r => {
          console.log(r);
          this.tableData = r.data.rows;
          this.total = r.data.total;
        }).catch(e => {
        })
      },
      onSubmit() {
        let params = {
          bookname: this.bookname,
        }
        // 调用查询方法
        this.query(params);
      },
      handleSizeChange(r) { //当页大小发生变化
        // 输出查看
        console.log("当前页大小:" + r);
        let params = {
          bookname: this.bookname,
          rows: r,
          page: this.page
        }
        // 调用查询方法
        this.query(params);
      },
      handleCurrentChange(p) { //当当前页页码大小发生变化
        // 输出查看
        console.log("当前页码:" + p);
        let params = {
          bookname: this.bookname,
          page: p,
          rows: this.rows
        }
        // 调用查询方法
        this.query(params);
      }
    },
    created() {
      // 调用查询方法
      this.query({});
      this.types = [{
        id: 1,
        name: '爱情'
      }, {
        id: 2,
        name: '玄幻'
      }, {
        id: 3,
        name: '激情'
      }]
    }
  }
</script>

效果展示

4. 编写删除功能的代码及提示框

删除功能的方法

del(idx, row) {
        this.$confirm('此操作将永久删除id为'+row.id+', 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
           let url = this.axios.urls.Book_DEL;
          this.axios.post(url, {id:row.id}).then(r => {
            console.log(r);
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.query({}); //刷新
          }).catch(e => {
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },

展示效果

二、表单验证

在form表单中要包含:rules="rules" ref="ruleForm"代码。

Form 组件提供了表单验证的功能,只需要通过 属性传入约定的验证规则,并将 Form-Item 的 属性设置为需校验的字段名即可。校验规则参见 async-validatorrulesprop

功能js编写

规则
rules: {
          bookname: [{
              required: true,
              message: '请输入书籍名称',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 5,
              message: '长度在 1 到 9 个字符',
              trigger: 'blur'
            }
          ],
          price: [{
              required: true,
              message: '请输入书籍价格',
              trigger: 'blur'
            }],
          booktype: [{
            required: true,
            message: '请选择书籍类型',
            trigger: 'change'
          }]
        }

启用表单
this.$refs[formName].validate((valid) => {
          if (valid) {
            alert('submit!');
          } else {
            console.log('error submit!!');
            return false;
          }
        });

效果

今天的分享到此结束,感谢支持,三连加关注就是对博主最大的支持。

 

目录
相关文章
|
1天前
|
数据采集 JavaScript 前端开发
Vue框架的优缺点是什么
【7月更文挑战第5天】 Vue框架:组件化开发利于重用与扩展,响应式数据绑定简化状态管理;学习曲线平缓,生态系统丰富,集成便捷,且具性能优化手段。缺点包括社区规模相对小,类型支持不足(Vue 3.x改善),路由和状态管理需额外配置,SEO支持有限。随着发展,部分缺点正被克服。
7 1
|
1天前
|
JavaScript
Vue卸载eslint的写法,单独安装eslint,单独卸载eslint
Vue卸载eslint的写法,单独安装eslint,单独卸载eslint
|
1天前
|
JavaScript
青戈大佬安装Vue,无Eslint安装版,vue2安装,vue2无eslint,最简单配置Vue安装资料
青戈大佬安装Vue,无Eslint安装版,vue2安装,vue2无eslint,最简单配置Vue安装资料
|
1天前
|
JavaScript 前端开发 开发工具
如何学习vue框架
【7月更文挑战第5天】 - 先学HTML/CSS/JS基础和前端工程化工具(npm, webpack, Git)。 - 从Vue官方文档学习基础,包括指令、组件、响应式系统。 - 深入研究Vue Router和Vuex,掌握路由管理和状态管理。 - 学习自定义指令和Mixins,优化性能技巧。 - 实战项目练习,加入Vue社区,阅读相关资源,提升技能。 - 关注Vue生态,持续实践和创新,以适应不断发展的框架。
5 0
|
2天前
|
JavaScript 区块链
vue 自定义网页图标 favicon.ico 和 网页标题
vue 自定义网页图标 favicon.ico 和 网页标题
9 1
|
1天前
|
JavaScript
This dependency was not found:* vue/types/umd in ./src/router/index.jsTo install it, you can run
This dependency was not found:* vue/types/umd in ./src/router/index.jsTo install it, you can run
This dependency was not found:* vue/types/umd in ./src/router/index.jsTo install it, you can run
|
2天前
|
存储 JavaScript 数据安全/隐私保护
vue实战——登录【详解】(含自适配全屏背景,记住账号--支持多账号,显隐密码切换,登录状态保持)
vue实战——登录【详解】(含自适配全屏背景,记住账号--支持多账号,显隐密码切换,登录状态保持)
12 1
|
2天前
|
JavaScript
vue实战——404页面模板001——男女手电筒动画
vue实战——404页面模板001——男女手电筒动画
8 1
|
1天前
|
缓存 JavaScript 算法
vue 性能优化
vue 性能优化
10 0
|
2天前
|
JavaScript 前端开发 程序员
Vue组件化、单文件组件以及使用vue-cli(脚手架)
Vue组件化、单文件组件以及使用vue-cli(脚手架)
12 0