笔耕不辍 elementUI el-tree实现懒加载和直接查询实现

懒加载实现(点击一级才出现二级的数据)

前端vue实现

1. vue的template里面的代码

    <el-dialog
      v-dialogDrag
      title="医院代码索引"
      :visible.sync="hscodeDialogFormVisible"
      class="dialog"
      width="40%"
    >

      <div class="device-tree">
        <el-scrollbar style="height:100%">
          <el-input
  placeholder="输入关键字进行模糊查询"
  v-model="filterText">
</el-input>
          <el-tree :data="treeData" :props="defaultProps" @node-click="handleNodeClick" lazy :load="loadNode"
          :filter-node-method="filterNode" ref="tree"></el-tree>
        </el-scrollbar>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button plain @click="hscodeDialogFormVisible = false" size="small">清空选择</el-button >
        <!-- <el-button type="danger" @click="sortSavebtn">确 定</el-button> -->
      </div>
    </el-dialog>


2vue文件里面的data数据

data() {
    return {
      isadd:false,
      // 列表数据
      dataList: [],

      // 公共数据
      commonData: {
        finished: "未完成",
        chgtyp: "",
        recdte: "",
        newcompany: "",
        rscdno: "",
        calname: "",
        ccbhsadd: "",
        hscode: "",
        tsalesunt: "",
        hsname: "",
        hsadd: "",
        hsnname: "",
        hsnadd: "",
        chgvdte: "",
        trectyp: "",
        sumind: "",
        hqind: "",
        hclass: "",
        hscodtyp: "",
     
      },

      adddteValue: "", //新增日期
      conditions: maintainCondition.conditions, //搜索条件
      // fence: maintainCondition.injuryCodeUpholds,//栏位

      form: {
        //高级搜索
        tableData: [],
        //排序
        sortTableData: [],
      },

      // checkList: ["排序字段1"],

      // 高级搜索滑动框值
      fields: [
        {
          label: "变更类型",
          value: "lchi.chgtyp",
        },
        {
          label: "记录日期",
          value: "lchi.recdte",
        },
        {
          label: "医院代码",
          value: "lchi.hscode",
        },
        {
          label: "医院名称",
          value: "lchi.hsname",
        },
        {
          label: "医院地址",
          value: "lchi.hsadd",
        },
        {
          label: "医院新名称",
          value: "lchi.hsnname",
        },
        {
          label: "变更生效日",
          value: "lchi.chgvdte",
        },
        {
          label: "状态",
          value: "lchi.finished",
        },
      ],

      // 排序滑动框值
      fields2: [
        {
          label: "序号",
          value: "lchi.id",
        },
        {
          label: "变更类型",
          value: "lchi.chgtyp",
        },
        {
          label: "记录日期",
          value: "lchi.recdte",
        },
        {
          label: "医院代码",
          value: "lchi.hscode",
        },
        {
          label: "医院名称",
          value: "lchi.hsname",
        },
        {
          label: "医院地址",
          value: "lchi.hsadd",
        },
        {
          label: "医院新名称",
          value: "lchi.hsnname",
        },
        {
          label: "医院新地址",
          value: "lchi.hsnadd",
        },
        {
          label: "变更生效日",
          value: "lchi.chgvdte",
        },
        {
          label: "医院类别",
          value: "lchi.trectyp",
        },
        {
          label: "赔付范围",
          value: "lchi.sumind",
        },
        {
          label: "医院品质",
          value: "lchi.hqind",
        },
        {
          label: "医院级别",
          value: "lchi.hclass",
        },
        {
          label: "代码类型",
          value: "lchi.hscodtyp",
        },
      
      ],

      dialogFormVisible: false,
      sortDialogFormVisible: false,
      hscodeDialogFormVisible: false,//医院代码索引弹框
      page: {
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
      },
      nums:"",
      flage:"",
      flageApi:true,
      newcompanyOptions:[],//公司别
      treeData: [],
      hscode:"",
      hscodeindex:"",

      defaultProps: {
        children: 'children',
        label: 'label'
      },
      filterText: '',


    };
  },




3vue文件里面的methods方法

handleNodeClick(data) {
      console.log(data.treelevel);
       console.log(data,"data----------");

      if(data.treelevel == 1){
        this.hospitalCodeIndexFn(data.hscode,data.sort)
      }
      if(data.treelevel == 2){
         this.hscodeDialogFormVisible = true
        this.hospitalCodeIndexFn2(data.hscode,data.sort)
      }
      if(data.treelevel == 3){
        // let newdata = {
        //     hscode:data.hscode
        //   }
        // this.hscode = data.hscode
        this.dataList[this.hscodeindex].hscode = data.hscode
        this.dataList[this.hscodeindex].hsname = data.hsname
        this.dataList[this.hscodeindex].hsadd = data.hsadd
        this.dataList[this.hscodeindex].trectyp = data.trectyp
        this.dataList[this.hscodeindex].sumind = data.sumind
        this.dataList[this.hscodeindex].hqind = data.hqind
        this.dataList[this.hscodeindex].hclass = data.hclass
        this.dataList[this.hscodeindex].hscodtyp = data.hscodtyp
        this.dataList[this.hscodeindex].chgtyp = data.chgtyp//变更类型
        // this.dataList[this.hscodeindex].hscode = data.hscode
        this.hscodeDialogFormVisible = false
      }

    },

    // 医院代码索引/获取市
    hscodeClick(num,index){
      this.hscodeindex = index
        this.treeData = []
        this.hscodeDialogFormVisible = true
        this.$store.dispatch("loading/CHANGE_LOADING", true);
        let params = {
          pid:"source"
        };
        hospitalCodeIndexApi(params)
          .then((res) => {
            this.$store.dispatch("loading/CHANGE_LOADING", false);
            if (res.resultCode === 0) { 
              let newData = res.data
              newData.forEach((e,eindex)=>{
                this.treeData.push({label:e.hscode + e.hsname,hscode:e.hscode,treelevel:1,sort:eindex,children:[]})
              })
            }
          })
          .catch(() => {this.$store.dispatch("loading/CHANGE_LOADING", false)});
      
    },

    // 获取县
    hospitalCodeIndexFn(hscode,id){     
      let params = {
        pid:hscode
      }
      hospitalCodeIndexApi(params)
        .then((res) => {
          this.$store.dispatch("loading/CHANGE_LOADING", false);
          if (res.resultCode === 0) {
            // console.log(res.data);
            let newData = res.data
            newData.forEach((e,eindex)=>{
              this.$set(e,"label",e.hscode + e.hsname)
              this.$set(e,"treelevel",2)
              this.$set(e,"sort",eindex)
              this.$set(e,"children",[])
            })
            this.treeData.forEach((i,iindex)=>{
              if(i.sort == id){
                i.children = newData
              }
            })
          }
        })
        .catch(() => {this.$store.dispatch("loading/CHANGE_LOADING", false)}
      );
    },

    // // 获取医院
    hospitalCodeIndexFn2(hscode,id){
      let params = {
        pid:hscode
      }
      hospitalCodeIndexApi(params)
        .then((res) => {
          this.$store.dispatch("loading/CHANGE_LOADING", false);
          if (res.resultCode === 0) {
            // console.log(res.data);
            let newData = res.data
            newData.forEach((e,eindex)=>{
              this.$set(e,"label",e.hscode + e.hsname)
              this.$set(e,"treelevel",3)
              this.$set(e,"sort",eindex)
              this.$set(e,"children",[])
            })

            this.treeData.forEach((i,iindex)=>{
              if(newData[0].hscode.indexOf(i.hscode) != -1){
                i.children.forEach((j,jindex)=>{
                  if(j.sort == id){
                    console.log(j.hscode);
                    j.children= newData
                  }
                })
              }
            })
          }
        })
        .catch(() => {this.$store.dispatch("loading/CHANGE_LOADING", false)}
      );

      
        
    },

4vue文件里面的监听方法

 watch: {
      filterText(val) {
        this.$refs.tree.filter(val);
      }
    },


注意因为是懒加载所以需要每次加载完成都需要使弹窗置为true

后端实现

封装的工具类:

package com.citicpru.clmwork.utils;

import lombok.Data;
import lombok.Getter;

/*
* author: monkey
* 用于接收post请求的单个参数
* */
@Data
@Getter
public class IdBean {
    private String pid;
}


1. controller层

@PostMapping(value = "/hospitalCodeIndex")
    @ApiOperation(value = "医院代码索引", response = ObjectRestResponse.class)
    public ObjectRestResponse hospitalCodeIndex(@ApiParam(value = "医院代码索引")
                                                    @RequestBody IdBean idBean) {
        String pid = idBean.getPid();
        if(pid == null || "".equals(pid)){
            pid = "source";
        }
        ObjectRestResponse restResponse = new ObjectRestResponse();
        String length = "";
        int end = 0;
        if ("source".equals(pid)) {
            end = 0;
            length = "2";
        } else {
            end = pid.trim().length();
            if (end == 2)
                length = "4";
            if (end == 4)
                length = "6";
        }
        List<ClmHospitalLccc> json=hospitalMtnBiz.index(length,end,pid);
        restResponse.setData(json);

        return restResponse;
    }



2.service层

public  List<ClmHospitalLccc>  index(String length, Integer end,String flag){
        String condition = "length(rtrim(lcc.hscode)) = " + length;
        if (end != 0) {
            condition += " and substring(lcc.hscode,1," + end + ") = '" + flag
                    + "' ";
        }
//        List<hospitalCodeIndexVO> indexVOList=null;

//        List insList = new ArrayList();
        List<ClmHospitalLccc> lcccList=clmHospitalLcccMapper.queryAsyncLcccTree1(condition);
//        for (hospitalCodeIndexVO lccc:lcccList){
            List twoList = new ArrayList();
//            List<hospitalCodeIndexVO> lcccList1=clmHospitalLcccMapper.queryAsyncLcccTree(2,lccc.getHscode(),"4");
//            lccc.setLcccList(lcccList1);
//            for(hospitalCodeIndexVO lccc1:lcccList1){
//                List<hospitalCodeIndexVO> lcccList2=clmHospitalLcccMapper.queryAsyncLcccTree(4,lccc1.getHscode(),"6");
//                lccc1.setLcccList(lcccList2);
//            }
//        }

//        StringBuffer sb = new StringBuffer();
//        sb.append("[");
//        if (lccc != null) {
//            for (int i = 0; i < lccc.size(); i++) {
//                ClmHospitalLccc lcccInfo = (ClmHospitalLccc) lccc.get(i);
//                sb.append(",{'id':'");
//                sb.append(String.valueOf(lcccInfo.getHscode()).trim());
//                sb.append("','name':'");
//                sb.append(String.valueOf(lcccInfo.getHsname()).trim());
//                sb.append("','pect':'','childrenItem':'");
//
//                if ("6".equals(length.trim()))
//                    sb.append("0'}");
//                else
//                    sb.append("1'}");
//            }
//        }
//        sb.append("]");
        return lcccList;
    }





3Mapper层


List<ClmHospitalLccc> queryAsyncLcccTree1(@Param("condition")String condition);


4xml层

    <select id="queryAsyncLcccTree1" resultMap="clmHospitalLcccMap" parameterType="java.lang.String">
        select * from
        clm_hospital_lccc as lcc where status=1 and
        <![CDATA[  ${condition}  ]]>
        order by hscode

    </select>




<![CDATA[ ${condition} ]]> 这个是查询复杂的条件封装的,英文意思complex Data

直接全部查询

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>分类管理</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css">
    		
		<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
        <!-- 引入样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!-- 引入组件库 -->
    <script src="https://unpkg.com/element-ui/lib/index.js">
      
    </script>
    
	<script src="static/js/base.js"></script>
    <script src="static/js/axios.min.js"></script>
    <style>
        .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
    </style>
</head>
<body>
  

<div id="app">  
  <el-alert
  title="商品分类管理页面"
  description="对商品的分类进行管理"
  type="success"
  description="对商品的多级分类进行管理"
  show-icon>
  </el-alert>
  <h2 class="ui teal header" style="color: teawl;margin-top: 30px;text-align: center;">欢迎来到分类管理页面</h2>
   

  <!-- {{this.categories}} -->

	<!-- 通过一个li遍历多个 -->

    <div class="category">
			  <h3 class="ui teal header">商品多级分类名称:</h3>	

              <!-- 树形控件实现商品分类 -->
              <el-input
  placeholder="输入关键字进行过滤"
  v-model="filterText">
</el-input>

<el-tree
show-checkbox
  class="filter-tree"
  :data="data1"
  node-key="id"
  :props="defaultProps"
  :filter-node-method="filterNode"
  ref="tree"

  :expand-on-click-node="false"
  :render-content="renderContent"
  

  
  >
</el-tree>

          
    </div>




</div>
<script src="static/js/cookie_utils.js"></script>

		<script src="static/js/base.js"></script>

    <script>
        new Vue({
            el:'#app',
            data:{
              data1:[],
                message:"hello",
                dataList:[],
                categories:[],
                inputCategoryLevel1:true,
                token:"",
                userId:"",
                disabled:true,
                filterText:"",
                data: [{
          id: 1,
          label: '一级 1',
          children: [{
            id: 4,
            label: '二级 1-1',
            children: [{
              id: 9,
              label: '三级 1-1-1'
            }, {
              id: 10,
              label: '三级 1-1-2'
            }]
          }]
        }, {
          id: 2,
          label: '一级 2',
          children: [{
            id: 5,
            label: '二级 2-1'
          }, {
            id: 6,
            label: '二级 2-2'
          }]
        }, {
          id: 3,
          label: '一级 3',
          children: [{
            id: 7,
            label: '二级 3-1'
          }, {
            id: 8,
            label: '二级 3-2'
          }]
        }],
        defaultProps: {
          children: 'categories',
          label: 'categoryName',
        }

            },
              watch: {
      filterText(val) {
        this.$refs.tree.filter(val);
      }
    },
     created(){
      //  商品分类相关参数
                    this.showCategorires();
                },
            methods:{
                filterNode(value, data) {
                  console.log(value);
        if (!value) return true;
        return data.categoryName.indexOf(value) !== -1;
      },

append(data) {
        const newChild = { id: id++, label: 'testtest', children: [] };
        if (!data.children) {
          this.$set(data, 'children', []);
        }
        data.children.push(newChild);
      },

      remove(node, data) {
        const parent = node.parent;
        const children = parent.data.children || parent.data;
        const index = children.findIndex(d => d.id === data.id);
        children.splice(index, 1);
      },


      // ---------------

                showCategorires(){
                    let token=getCookieValue("token");
                    console.log(token);
                    this.token  = token;
                    let userId=getCookieValue("userId");
                    console.log(userId,"UserId");
                    this.userId=userId;
                    var url22=baseUrl+"index/categorylist";
                    axios({
								url:url22,
								method:"post",
								headers:{
									token:this.token
								},
								data:this.userId
							}).then(res=>{
  console.log(res.data.data);
  this.categories=res.data.data;
  this.data1 = res.data.data;
  this.dataList = this.categories.filter(function (type) {
            return type.parentId == "1";
          });
          console.log( this.categories,"categoryList")
  this.categories.forEach(element => {
  
      
  });

  
})
                },

                UpdateHandle(row) {  
                    row.disabled = false;   
                    this.inputCategoryLevel1=false;
                    console.log(row);
                  
                },
               
            }
        })
    </script>
    
</body>
</html>



后端的数据(通过子查询查询出来)

controller


    @ApiOperation("商品分类查询接口")
    @PostMapping("/categorylist")
    public ResultVO queryAllCategory(@RequestBody String userId,@RequestHeader String token){
        return categoryService.listcategories(userId,token);
    }



service


  public ResultVO listcategories(String userId,String token);

serviceiml


      public ResultVO listcategories(String userId,String token) {

            List<CategoryVO> categoryVOS=categoryMapper.selectAllCategories2(0);;
//      System.out.println(categoryVOS);
            ResultVO resultVO = new ResultVO(ResultStatus.OK, "success", categoryVOS);

            return resultVO;





    }


mapper


//    子查询
    public List<CategoryVO> selectAllCategories2(int parentId);

mapper.xml

<!--  使用子查询实现的分类列表查询-->
  <resultMap id="CategoryMap2" type="com.qfedu.fmmall.entity.CategoryVO">
    <!--
      WARNING - @mbg.generated
    -->
    <id column="category_id" jdbcType="VARCHAR" property="categoryId" />
    <result column="category_name" jdbcType="VARCHAR" property="categoryName" />
    <result column="category_level" jdbcType="INTEGER" property="categoryLevel" />
    <result column="parent_id" jdbcType="INTEGER" property="parentId" />
    <result column="category_icon" jdbcType="VARCHAR" property="categoryIcon" />
    <result column="category_slogan" jdbcType="VARCHAR" property="categorySlogan" />
    <result column="category_bg_color" jdbcType="VARCHAR" property="categoryBgColor" />
    <collection property="categories" column="category_id" select="com.qfedu.fmmall.dao.CategoryMapper.selectAllCategories2"/>

<!--  这里的column="category_id"将等于
//    子查询
    public List<CategoryVO> selectAllCategories2(int parentId);里面的parentId;
-->

  </resultMap>

  <!--  使用子查询实现的分类列表查询-->
  <select id="selectAllCategories2" resultMap="CategoryMap2">
    select

     category_id,
category_name,
category_level,
parent_id,
category_icon,
category_slogan,
category_pic,
category_bg_color


from category where parent_id=#{parentId};
  </select>

VO

package com.qfedu.fmmall.entity;

import javax.persistence.Column;
import javax.persistence.Id;
import java.util.List;

public class CategoryVO {

    @Override
    public String
    toString() {
        return "CategoryVO{" +
                "categoryId='" + categoryId + '\'' +
                ", categoryName='" + categoryName + '\'' +
                ", categoryLevel=" + categoryLevel +
                ", parentId=" + parentId +
                ", categoryIcon='" + categoryIcon + '\'' +
                ", categorySlogan='" + categorySlogan + '\'' +
                ", categoryBgColor='" + categoryBgColor + '\'' +

                '}';
    }

    /**
     * 商品分类 id
     */
    @Id
    @Column(name = "category_id")
    private String categoryId;

    /**
     * 商品分类名称
     */
    @Column(name = "category_name")
    private String categoryName;

    /**
     * 商品分类层级
     */
    @Column(name = "category_level")
    private Integer categoryLevel;

    /**
     * 父层id
     */
    @Column(name = "parent_id")
    private Integer parentId;

    /**
     * 分类图标
     */
    @Column(name = "category_icon")
    private String categoryIcon;

    /**
     * 口号
     */
    @Column(name = "category_slogan")
    private String categorySlogan;

    /**
     * 背景颜色
     */
    @Column(name = "category_bg_color")
    private String categoryBgColor;


    private List<CategoryVO> categories;

    public List<CategoryVO> getCategories() {
        return categories;
    }

    public void setCategories(List<CategoryVO> categories) {
        this.categories = categories;
    }

    /**
     * 获取商品分类 id
     *
     * @return category_id - 商品分类 id
     */
    public String getCategoryId() {
        return categoryId;
    }

    /**
     * 设置商品分类 id
     *
     * @param categoryId 商品分类 id
     */
    public void setCategoryId(String categoryId) {
        this.categoryId = categoryId == null ? null : categoryId.trim();
    }

    /**
     * 获取商品分类名称
     *
     * @return category_name - 商品分类名称
     */
    public String getCategoryName() {
        return categoryName;
    }

    /**
     * 设置商品分类名称
     *
     * @param categoryName 商品分类名称
     */
    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName == null ? null : categoryName.trim();
    }

    /**
     * 获取商品分类层级
     *
     * @return category_level - 商品分类层级
     */
    public Integer getCategoryLevel() {
        return categoryLevel;
    }

    /**
     * 设置商品分类层级
     *
     * @param categoryLevel 商品分类层级
     */
    public void setCategoryLevel(Integer categoryLevel) {
        this.categoryLevel = categoryLevel;
    }

    /**
     * 获取父层id
     *
     * @return parent_id - 父层id
     */
    public Integer getParentId() {
        return parentId;
    }

    /**
     * 设置父层id
     *
     * @param parentId 父层id
     */
    public void setParentId(Integer parentId) {
        this.parentId = parentId;
    }

    /**
     * 获取分类图标
     *
     * @return category_icon - 分类图标
     */
    public String getCategoryIcon() {
        return categoryIcon;
    }

    /**
     * 设置分类图标
     *
     * @param categoryIcon 分类图标
     */
    public void setCategoryIcon(String categoryIcon) {
        this.categoryIcon = categoryIcon == null ? null : categoryIcon.trim();
    }

    /**
     * 获取口号
     *
     * @return category_slogan - 口号
     */
    public String getCategorySlogan() {
        return categorySlogan;
    }

    /**
     * 设置口号
     *
     * @param categorySlogan 口号
     */
    public void setCategorySlogan(String categorySlogan) {
        this.categorySlogan = categorySlogan == null ? null : categorySlogan.trim();
    }

    /**
     * 获取背景颜色
     *
     * @return category_bg_color - 背景颜色
     */
    public String getCategoryBgColor() {
        return categoryBgColor;
    }

    /**
     * 设置背景颜色
     *
     * @param categoryBgColor 背景颜色
     */
    public void setCategoryBgColor(String categoryBgColor) {
        this.categoryBgColor = categoryBgColor == null ? null : categoryBgColor.trim();

    }
}



  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

有时间指导毕业设计

觉得写的好的话可以给我打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值