Vue 实现表单的增删改查功能及表单的验证

简介: Vue 实现表单的增删改查功能及表单的验证

前言:

上一篇我们已经将前端表单的数据和后端的数据交互了,今天我们就继续开发功能来实现表单的增删改查功能及表单的验证

一,表单的增删改查功能

新增

去官网找模版:

1.1添加新增按钮:

1.2添加新增弹窗点击事件:

1.3添加新增提交功能,刷新表单

// 确认新增
      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
            };
            this.axios.post(url, params).then(r => {
              console.log(r);
              this.clear();
              this.query({});
            }).catch(e => {
            });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      }

二,表单的验证

优化:当我们点击新增区提交的时候,我们就必须要设置表单的规则去验证,不然的话我们的功能就少了体验感,后台保存的数据可能有问题!!!

通过查看官网:

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

规则

编写规则

注意:

表单重置时必须先清空表单验证信息,再清空表单数据信息,通过form表单的ref属性来清空表单验证信息

代码:

this.$refs['需要验证的表单名称'].validate((valid) => {
    if (valid) {
      //验证通过
      alert('submit!');
    } else {
      //验证失败
      console.log('error submit!!');
        return false;
    }
});

具体代码:

BookList.vue

<template>
  <div class="books" style="padding: 20px;">
    <!-- 搜索框 -->
    <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" size="small" plain @click="open">新增</el-button>
      </el-form-item>
    </el-form>
    <!-- 数据表格 -->
        <template>
          <el-table :data="tableData" border style="width: 100%">
            <el-table-column align="center" type="selection" min-width="1">
            </el-table-column>
            <el-table-column sortable prop="id" label="编号ID" min-width="2">
            </el-table-column>
            <el-table-column sortable prop="bookname" label="书籍名称" min-width="2">
            </el-table-column>
            <el-table-column sortable prop="price" label="书籍价格" min-width="2">
            </el-table-column>
            <el-table-column sortable prop="booktype" label="书籍类别" min-width="2">
            </el-table-column>
            <el-table-column label="操作" min-width="2">
              <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>
          </el-table>
        </template>
    <!-- 分页 -->
    <div class="block">
      <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" :rules="rules" ref="book">
        <el-form-item label="书籍编号" :label-width="formLabelWidth" :disabled="true">
          <el-input :value="book.id" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="书籍名称" :label-width="formLabelWidth" prop="bookname">
          <el-input v-model="book.bookname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="书籍价格" :label-width="formLabelWidth" prop="price">
          <el-input v-model="book.price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="书籍类别" :label-width="formLabelWidth" prop="booktype">
          <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: [],
        page: 1,
        rows: 10,
        total: 0,
        title: '新增窗口',
        dialogFormVisible: false,
        formLabelWidth: '100px',
        types: [],
        book: {
          id: '',
          bookname: '',
          price: '',
          booktype: ''
        },
        rules: {
          bookname: [{
            required: true,
            message: '请输入书籍名称',
            trigger: 'blur'
          }, ],
          price: [{
            required: true,
            message: '请输入书籍价格',
            trigger: 'blur'
          }, ],
          booktype: [{
            required: true,
            message: '请选择书籍类别',
            trigger: 'blur'
          }, ]
        }
      }
    },
    methods: {
      // 删除
      handleDelete(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.query({});
          }).catch(e => {
          });
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      // 确认新增
      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
            };
            this.axios.post(url, params).then(r => {
              console.log(r);
              this.clear();
              this.query({});
            }).catch(e => {
            });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      // 初始化窗口
      clear() {
        this.dialogFormVisible = false;
        this.title = '新增窗口',
          this.book = {
            id: '',
            bookname: '',
            price: '',
            booktype: ''
          }
      },
      // 打开窗口的方法
      open(idx, row) {
        this.dialogFormVisible = true;
        // console.log(idx);
        // console.log(row)
        if (row) {
          this.title = '编辑窗口';
          this.book.id = row.id;
          this.book.bookname = row.bookname;
          this.book.price = row.price;
          this.book.booktype = row.booktype;
        }
      },
      // 当前页大小
      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.BOOK_LIST;
        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);
      }
    },
    created() {
      this.query({});
      this.types = [{
        id: 1,
        name: '玄幻'
      }, {
        id: 2,
        name: '逆天'
      }, {
        id: 3,
        name: '抗日'
      }, {
        id: 4,
        name: '和平'
      }, {
        id: 5,
        name: '无敌'
      }];
    }
  }
</script>
<style>
</style>

action.js

/**
 * 对后台请求的地址的封装,URL格式如下:
 * 模块名_实体名_操作
 */
export default {
  'SERVER': 'http://localhost:8080', //服务器
  'SYSTEM_USER_DOLOGIN': '/user/userLogin', //登陆
  'SYSTEM_USER_DOREG': '/user/userRegister', //注册
  'SYSTEM_MENUS': '/module/queryRootNode', //左侧菜单树
  'BOOK_LIST': '/book/queryBookPager', //数据表格
  'BOOK_ADD': '/book/addBook', //数据增加
  'BOOK_UPD': '/book/editBook', //数据修改
  'BOOK_DEL': '/book/delBook', //数据删除
  'getFullPath': k => { //获得请求的完整地址,用于mockjs测试时使用
    return this.SERVER + this[k];
  }
}

案例效果展示:

 

三,总结:

  1. 快速开发:Element框架提供了丰富的组件和样式库,可以快速构建漂亮、一致的界面。开发人员无需从头开始编写每个组件的样式和交互逻辑,大大节省了开发时间。
  2. 响应式设计:Element框架支持响应式布局,自动适应不同的屏幕尺寸和设备类型。这意味着你的应用程序可以在桌面、平板和移动设备上以一致的方式运行,提供更好的用户体验。
  3. 可定制性:尽管Element框架提供了一套美观的默认主题和组件样式,但你也可以根据自己的需求进行定制。你可以自定义样式、颜色和布局来匹配你的品牌或项目风格。
  4. 生态系统丰富:Element框架生态系统庞大,有很多第三方的插件和扩展可供选择。这些插件和扩展可以帮助你快速实现一些高级功能和特效,提升开发效率。

需要注意的事项包括:

  1. 版本兼容性:确保使用的Element框架版本与你的项目兼容。不同版本之间可能存在一些API变化或bug修复,需要注意及时更新。
  2. 组件选择:了解Element框架提供的组件,并选择合适的组件来满足你的需求。不要过度依赖框架提供的组件,有时可能需要自定义组件来满足特定的需求。
  3. 性能优化:Element框架虽然功能强大,但有时可能会影响页面加载速度和性能。在使用框架时要注意代码优化,减少不必要的资源加载和渲染,提高应用程序的性能。

总结起来,学习和使用Element框架可以带来快速开发、响应式设计、可定制性和丰富的生态系统等好处。同时,在版本兼容性、组件选择和性能优化等方面需要注意。希望这些信息对你有帮助!如果有其他问题,请随时问我。

目录
相关文章
|
2天前
|
资源调度 JavaScript 前端开发
【vue】vue中的路由vue-router,vue-cli脚手架详细使用教程
【vue】vue中的路由vue-router,vue-cli脚手架详细使用教程
|
2天前
|
JavaScript 前端开发
vue组件化开发流程梳理,拿来即用
vue组件化开发流程梳理,拿来即用
|
2天前
|
JavaScript Go
Vue路由跳转及路由传参
Vue路由跳转及路由传参
|
3天前
|
JavaScript 前端开发 BI
采用前后端分离Vue,Ant-Design技术开发的(手麻系统成品源码)适用于三甲医院
开发环境 技术架构:前后端分离 开发语言:C#.net6.0 开发工具:vs2022,vscode 前端框架:Vue,Ant-Design 后端框架:百小僧开源框架 数 据 库:sqlserver2019
采用前后端分离Vue,Ant-Design技术开发的(手麻系统成品源码)适用于三甲医院
|
5天前
|
监控 JavaScript
Vue中的数据变化监控与响应——深入理解Watchers
Vue中的数据变化监控与响应——深入理解Watchers
|
存储 JavaScript 网络架构
Vue3新增功能特性
Vue3相比Vue2更新技术点
|
6天前
|
JavaScript
【vue】如何跳转路由到指定页面位置
【vue】如何跳转路由到指定页面位置
9 0
|
6天前
|
JSON JavaScript 前端开发
【vue】假数据的选择和使用
【vue】假数据的选择和使用
12 1
|
6天前
|
JavaScript 前端开发
【vue】iview如何把input输入框和点击输入框之后的边框去掉
【vue】iview如何把input输入框和点击输入框之后的边框去掉
12 0
|
5天前
|
JavaScript 安全 前端开发
Vue 项目中的权限管理:让页面也学会说“你无权访问!
Vue 项目中的权限管理:让页面也学会说“你无权访问!
15 3