vue+element-怎么实现常见的多条件查询

316 阅读3分钟
需求分析

我们在做项目的时候遇到的比较多就是查询数据,比较简单的是没有任何条件的查询,这样的是最基础的,也是最好做的,一般就是直接一个get方法就可以直接实现了,只需要调一下接口就可以的,稍微复杂一点的就是单条件查询,其实我以前是写数据脚本的,也就是只写一个对数据库的CURD的操作的,那么我是稍微了解一些对于数据库的操作的,那么我们前端需要做的就是将需要的查询条件给到后端,后端通过连接数据库对数据库进行基本的操作,这样实现一个查询的过程,那么其实单条件查询也是比较简单的,查询中比较复杂的就是多条件查询了,什么时候会遇到多条件查询呢?内容比较多的,检索条件需要就可能比较多,需要同时满足多个条件的也是需要多条件查询的。

难点分析

其实多条件查询最大的难点在于怎么将用户选择的数据给后端,没有选择的数据不给,也就是说怎么写一个比较轻松简单的数据组合给到后端进行检索。

解决方案

第一种:全部给后端,后端自己进行检索哪些是有值的,哪些是没值的,但是一般后端是不同意的,因为他们不会那么麻烦的还要自己进行判断哪些是有数据的,哪些字段是没有数据的,他们要的就是你没有数据的字段就不要给我,给我的就一定是有数据的。这样的他们才比较容易进行检索。
第二种:写一个map遍历,对所有的数据进行非空判断,申请一个新的数组,有值的就push到信的数组里面,没有的就不进行任何的操作,用户每操作一次就push一次
第三种:看下面的源码

/**
 * @closeaccount_search 已结账的查询
 */
close_account_search(){
   let that = this;
   that.value_live_in = that.value_live_in  ? that.value_live_in : undefined;
   that.value_leave = that.value_leave ? that.value_leave : undefined;
   that.value_account = that.value_account ? that.value_account : undefined;
   that.name = that.name ? that.name : undefined;
   that.phone = that.phone ? that.phone : undefined;
   that.room_num  = that.room_num  ? that.room_num  : undefined;
   that.team_name = that.team_name ? that.team_name : undefined;
   let url = that.url + ':9519/v1/finance/account/full_info_page';
   that.$axios({
        method : 'post',
        url : url,
        data : {
          find_cond :
            JSON.stringify(
               {check_in_date :  that.value_live_in,leave_date :  that.value_leave,
                check_out_date :  that.value_account,name :  that.name,
                phone :  that.phone,room_num :  that.room_num,
                team_name :  that.team_name})
                }
   }).then((res)=>{
      console.info(res);
   }).catch((err)=>{
      console.error(err);
   })
},

PS:这里是需要解释一下,不然可能有的人是蒙蔽的,这里为什么要这么处理,简单的说一下,我们是自己的约定,后端要的是只要是等值查询的都必须是find_cond,他可以统一处理,这个不重要,我们正常写的时候是这样的:

close_account_search(){
   let that = this;
   let url = that.url + ':9519/v1/finance/account/full_info_page';
   that.$axios({
        method : 'post',
        url : url,
        data : {
                check_in_date :  that.value_live_in  ? that.value_live_in : undefined,
                leave_date :  that.value_leave ? that.value_leave : undefined,
                check_out_date :  that.value_account ? that.value_account : undefined,
                name :  that.name ? that.name : undefined,
                phone :  that.phone ? that.phone : undefined,
                room_num :  that.room_num  ? that.room_num  : undefined,
                team_name :  that.team_name ? that.team_name : undefined
                }
   }).then((res)=>{
      console.info(res);
   }).catch((err)=>{
      console.error(err);
   })
},

PS:解释一下,这里你们写的时候不要按照我的写的,我是应为写这个的时候,后端的接口没有好,我不知道字段是什么样子的,所以有些字段的名字是和后端不一样的,我们一般的约定是后端的字段和前端的字段是一样的,这样一是好调试,二是好维护,所以看思路,不要看代码风格和编码习惯。

这样写好以后,给后端的数据就是这样的:

{name:‘tom’,team_name:‘Test’}

因为是数据的双向绑定的,所以用户不选择的就是直接undefined,也就不会显示,就不会给后端传递,就实现了一个基本的多条件查询。