Vue中使用表单验证+CRUD

本文介绍了如何实现表格数据的增删改查功能,并结合后台数据接口展示了表单验证的步骤。包括后台的接口设计、前端的按钮事件、Dialog对话框的使用、表单验证以及操作的实现。详细讲解了新增、修改和删除操作的代码实现,提供了相应的前端UI交互效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 接上篇的数据表格与分页,今天我们给表格中的数据增删改查与表单验证

 一、后台数据接口

public class BookAction extends DispatcherAction implements ModelDriver<Book> {
	private Book book=new Book();
	private BookDao bookDao=new BookDao();
	private ObjectMapper mapper=new ObjectMapper();
	@Override
	public Book getModel() {
		return book;
	}

	public String queryBookPager(HttpServletRequest req,HttpServletResponse resp)
			throws ServletException,IOException{
		PageBean pageBean=new PageBean();
		pageBean.setRequest(req);
		List<Book> books = bookDao.queryBookPager(book, pageBean);
		Map<String,Object> map=new HashMap<String,Object>();
		Map<String,Object> data=new HashMap<String,Object>();
		data.put("rows", books);
		data.put("total", pageBean.getTotal());
		map.put("data", data);
		map.put("success", true);
		map.put("msg", "OK");
		mapper.writeValue(resp.getOutputStream(),map);
		return null;
	}
	public String addBook(HttpServletRequest req,HttpServletResponse resp)
			throws ServletException,IOException{
		Map<String,Object> json=new HashMap<String,Object>();
		try {
			bookDao.addBook(book);
			json.put("code","1");
			json.put("msg", "操作成功");
		} catch (Exception e) {
			json.put("code", "-1");
			json.put("msg", "操作失败");
			e.printStackTrace();
		}
		mapper.writeValue(resp.getOutputStream(),json);
		return null;
	}
	
	public String editBook(HttpServletRequest req,HttpServletResponse resp)
			throws ServletException,IOException{
		Map<String,Object> json=new HashMap<String,Object>();
		try {
			bookDao.editBook(book);
			json.put("code","1");
			json.put("msg", "操作成功");
		} catch (Exception e) {
			json.put("code", "-1");
			json.put("msg", "操作失败");
			e.printStackTrace();
		}
		mapper.writeValue(resp.getOutputStream(),json);
		return null;
	}
	public String delBook(HttpServletRequest req,HttpServletResponse resp)
			throws ServletException,IOException{
		Map<String,Object> json=new HashMap<String,Object>();
		try {
			bookDao.delBook(book);
			json.put("code","1");
			json.put("msg", "操作成功");
		} catch (Exception e) {
			json.put("code", "-1");
			json.put("msg", "操作失败");
			e.printStackTrace();
		}
		mapper.writeValue(resp.getOutputStream(),json);
		return null;
	}
}

二、新增

 1.添加新增按钮

<el-form-item>
   <el-button type="primary" @click="query(1)">查询</el-button>
   <el-button type="success" @click="open">新增</el-button>
</el-form-item>

在查询按钮的旁边加一个新增按钮,给按钮添加一个点击事件open

2.初始化数据

    data: function() {
      return {
        bookname: '',
        tableData:[],
        page:1,
        rows:10,
        total:0,
        title:'书本新增',
        dialogFormVisible:false,
        book:{
          id:'',
          bookname:'',
          price:'',
          booktype:''
        },
        formLabelWidth:'100px',
      }
    }

3. Dialog对话框

<el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false" @close="dialogClose">
      <el-form ref="book" :model="book">
        <el-form-item  label="书本编号" :label-width="formLabelWidth">
          <el-input readonly="readonly" v-model="book.id" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="bookname" label="书本名字" :label-width="formLabelWidth">
          <el-input v-model="book.bookname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="price" label="书本价格" :label-width="formLabelWidth">
          <el-input v-model="book.price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="booktype" label="书本类型" :label-width="formLabelWidth" >
          <el-select v-model="book.booktype" placeholder="请选择" style="width: 100%">
            <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="save">确 定</el-button>
      </div>
    </el-dialog>

 使用Dialog搭建新增与修改的页面

 Attributes(属性)

参数说明类型可选值默认值
visible是否显示 Dialog,支持 .sync 修饰符booleanfalse
titleDialog 的标题,也可通过具名 slot (见下表)传入string
widthDialog 的宽度string50%
fullscreen是否为全屏 Dialogbooleanfalse
topDialog CSS 中的 margin-top 值string15vh
modal是否需要遮罩层booleantrue
modal-append-to-body遮罩层是否插入至 body 元素上,若为 false,则遮罩层会插入至 Dialog 的父元素上booleantrue
append-to-bodyDialog 自身是否插入至 body 元素上。嵌套的 Dialog 必须指定该属性并赋值为 truebooleanfalse
lock-scroll是否在 Dialog 出现时将 body 滚动锁定booleantrue
custom-classDialog 的自定义类名string
close-on-click-modal是否可以通过点击 modal 关闭 Dialogbooleantrue
close-on-press-escape是否可以通过按下 ESC 关闭 Dialogbooleantrue
show-close是否显示关闭按钮booleantrue
before-close关闭前的回调,会暂停 Dialog 的关闭function(done),done 用于关闭 Dialog
center是否对头部和底部采用居中布局booleanfalse
destroy-on-close关闭时销毁 Dialog 中的元素booleanfalse

Slot(插槽)

name说明
Dialog 的内容
titleDialog 标题区的内容
footerDialog 按钮操作区的内容

Events(事件)

事件名称说明回调参数
openDialog 打开的回调
openedDialog 打开动画结束时的回调
closeDialog 关闭的回调
closedDialog 关闭动画结束时的回调

4.对话框的打开与关闭事件

    methods: {
      //对话框打开事件
      open:function(){
        this.dialogFormVisible=true;
      },
      //关闭对话框事件
      dialogClose:function(){
        //清空表单数据
        this.book={
          id:'',
          bookname:'',
          price:'',
          booktype:''
        };
        //清空表单
        this.$refs['book'].resetFields();
        //重置对话框标题
        this.title="新增书本";
      },
    }

5.确定按钮的点击事件

      //新增书本事件
      save:function(){
        //定义路径
        let url=this.axios.urls.BOOK_ALL;
        let methodName="addBook";
        if(this.title=="编辑书本"){
           methodName="editBook";
        }
        //定义请求参数
        this.book['methodName']=methodName;
        //ajax请求
        this.axios.post(url,this.book).then(resp=>{
          let data=resp.data;
          this.$message({
              message: data.msg,
              type: data.code==1?'success':'error'
          });
          if(data.code==1){
            //关闭对话框
            this.dialogFormVisible=false;
            //刷新数据
            this.query(this.page);
          }
        }).catch(err=>{
          console.log(err);
        });
      },
      

 确定按钮可能是新增也可能是修改

6.文本框和下拉框的表单验证

data: function() {
      return {
        bookname: '',
        tableData:[],
        page:1,
        rows:10,
        total:0,
        title:'书本新增',
        dialogFormVisible:false,
        book:{
          id:'',
          bookname:'',
          price:'',
          booktype:''
        },
        formLabelWidth:'100px',
        rules: {
          bookname: [
            { required: true, message: '请输入书本名称', trigger: 'blur' },
          ],
          price: [
            { required: true, message: '请输入书本价格', trigger: 'blur' },
            { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
          booktype: [
            { required: true, message: '请选择书本类型', trigger: 'change' }
          ],
        }
      }
    },

 注:

  1. 要给<el-form>标签加上ref属性与rules属性(rules的值必须与下面定义的值一样)
  2. 还要在<el-form-item>标签中添加prop属性,prop="此处的名字,必须与rules中定义的属性一致"
  3. trigger中值的含义
    事件名说明参数
    change用户确认选定的值时触发组件绑定值
    blur当 input 失去焦点时触发组件实例
    focus当 input 获得焦点时触发组件实例

7.判断表单验证是否成功

//新增书本事件
      save:function(){
        this.$refs['book'].validate((valid) => {
          if (valid) {
            //定义路径
            let url=this.axios.urls.BOOK_ALL;
            let methodName="addBook";
            if(this.title=="编辑书本"){
              methodName="editBook";
            }
            //定义请求参数
            this.book['methodName']=methodName;
            //ajax请求
            this.axios.post(url,this.book).then(resp=>{
              let data=resp.data;
              this.$message({
                  message: data.msg,
                  type: data.code==1?'success':'error'
              });
              if(data.code==1){
                //关闭对话框
                this.dialogFormVisible=false;
                //刷新数据
                this.query(this.page);
              }
            }).catch(err=>{
              console.log(err);
            });
          } else {
            alert('格式不正确!');
            return false;
          }
        });
      },

表单验证成功才能新增书本

 新增效果:

二、修改 

1.添加操作栏

    <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>

2.给修改方法定义事件

      //书本编辑
      handleEdit:function(row){
        //设置对话框为显示状态
        this.dialogFormVisible=true;
        //设置标题为编辑书本
        this.title="编辑书本";
        //赋值表单数据
        this.book={
          id:row.id,
          bookname:row.bookname,
          price:row.price,
          booktype:row.booktype
        };
      },

效果:

 

 三、删除

 1.给删除按钮定义事件

     //书本删除
      handleDelete:function(row){
        this.$confirm('删?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let url=this.axios.urls.BOOK_ALL;
          let params={
            id:row.id,
            methodName:'delBook'
          };
          this.axios.post(url,params).then(resp=>{
              let data=resp.data;
              this.$message({
                  message: data.msg,
                  type: data.code==1?'success':'error'
              });
              if(data.code==1){
                this.query(this.page);
              }
            }).catch(err=>{
              console.log(err);
            });
        }).catch(() => {});
      },

效果:

删除了编号为41的书

 然后他就无了

 博主水平有限,难免有错。欢迎评论交流

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值