Vue中使用表单验证+CRUD

Vue中使用表单验证+CRUD,第1张

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

 一、后台数据接口
public class BookAction extends DispatcherAction implements ModelDriver {
	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 books = bookDao.queryBookPager(book, pageBean);
		Map map=new HashMap();
		Map data=new HashMap();
		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 json=new HashMap();
		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 json=new HashMap();
		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 json=new HashMap();
		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.添加新增按钮

   查询
   新增

在查询按钮的旁边加一个新增按钮,给按钮添加一个点击事件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对话框

      
        
          
        
        
          
        
        
          
        
        
          
            
            
          
        
      
      
        取 消
        确 定
      
    

 使用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. 要给标签加上ref属性与rules属性(rules的值必须与下面定义的值一样)
  2. 还要在标签中添加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.添加 *** 作栏
    
        
        
      
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的书

 然后他就无了

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

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/915789.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-16
下一篇2022-05-16

发表评论

登录后才能评论

评论列表(0条)

    保存