Code Monkey home page Code Monkey logo

lazy-cascader's Introduction

lazy-cascader

ElementUI 级联选择组件(Cascader)懒加载的拓展

image.png

为什么会有这个组件?

首先我们要问ElementUI的Cascader级联选择器懒加载的时候有什么问题。

1、为什么懒加载,多选的时候没有自带回显逻辑?

2、懒加载的时候怎么才能搜索出未加载的选项?

为了解决这两个问题,我在网上翻了很多博客,虽然找到了回显的解决方案,但是似乎并不是很完美,或者有部分bug,甚至有些是无用的代码。

该组件如何使用?

1、推荐使用 yarn 或者 npm 安装

yarn add lazy-cascader

2、引用安装包并使用

 
 //引入组件
import LazyCascader from "lazy-cascader";

//声明组件
components: {
  LazyCascader
}

3、在template

<lazy-cascader v-model="category" :props="props"></lazy-cascader>

4、支持的属性

参数 说明 类型 可选值 默认值
v-model 选中项绑定值 - - -
props 配置选项,具体见下表 object - -
placeholder 输入框占位文本 string - 请选择
disabled 是否禁用 boolean - false
filterable 是否开启搜索 boolean - false
clearable 是否支持清空选项 boolean - false
width 组件的宽度,输入框和搜索框的宽度 string - 400px
suggestionsPopperClass 搜索下拉列表的类名 string - suggestions-popper-class,注:默认suggestions-popper-class的样式为width: auto!important;
searchWidth 搜索框宽度 string - -,注:取值方式为width: searchWidth | 100%
searchEmptyText 搜索框远程搜索无数据的时候展示的默认文案 string - 暂无数据

5、props配置项

参数 说明 类型 可选值 默认值
multiple 是否多选 boolean - false
checkStrictly 是否严格的遵守父子节点不互相关联 boolean - false
value 指定选项的值为选项对象的某个属性值 string - 'value'
label 指定选项标签为选项对象的某个属性值 string - 'label'
leaf 指定选项的叶子节点的标志位为选项对象的某个属性值 string - leaf
lazyLoad 加载动态数据的方法 function(nodeValue, resolve),node为当前点击的节点,resolve为数据加载完成的回调(必须调用),nodeValue根为0 - -
lazySearch 动态搜索数据的方法 function(queryString, callback),queryString为搜索时的关键字,callback为数据加载完成的回调(必须调用) - -

6、支持事件change,当选择的值发生变化是触发

7、注意事项 大部分配置参数都同ElementUI的Cascader级联选择器,可参考其文档ElementUI官方文档 lazySearch的callback返回一个数组,数组格式如下

//其中value和label键值同props配置项的参数一致
[{value:[1,2,3,4],label:["服装鞋包", "流行男鞋", "凉鞋", "沙滩鞋"]}]

Project setup

yarn install

Compiles and hot-reloads for development

yarn run serve

lazy-cascader's People

Contributors

spencer17x avatar zhuss avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

lazy-cascader's Issues

懒加载参数返回问题

懒加载第一个参数是选中的节点值,而非选中的node节点,导致懒加载如果不是一个接口,无法判断节点位置无法使用!

搜索-单选有延时

在单选-远程搜索时候 有使用问题

封装的组件内部调change的时机不对。
通过搜索面板来执行change,这个时候如果获取getCheckedNodes将是null
不过我注意到你在知乎上有回答:

https://zhuanlan.zhihu.com/p/297914302
YanYuanYanYuan回复四哥 (作者)06-22
单选的情况涉及时机的问题,会有几秒的延迟

对此,我稍微改了一下插件
lazy-cascader.vue

<template>
  <div class="lazy-cascader" :style="{ width: width }">
    <!-- 禁用状态 -->
    <div
        v-if="disabled"
        class="el-input__inner lazy-cascader-input lazy-cascader-input-disabled"
    >
      <span class="lazy-cascader-placeholder" v-show="placeholderVisible">
        {{ placeholder }}
      </span>
      <div class="lazy-cascader-tags" v-if="props.multiple">
        <el-tag
            class="lazy-cascader-tag"
            type="info"
            disable-transitions
            v-for="(item, index) in labelArray"
            :key="index"
            closable
        >
          <span> {{ item.label.join(separator) }}</span>
        </el-tag>
      </div>
      <div class="lazy-cascader-label" v-else>
        <el-tooltip
            placement="top-start"
            :content="labelObject.label.join(separator)"
        >
          <span>{{ labelObject.label.join(separator) }}</span>
        </el-tooltip>
      </div>
    </div>
    <!-- 禁用状态 -->
    <!-- 可选状态 -->
    <el-popover v-else trigger="click" placement="bottom-start" ref="popover">
      <!-- 搜索 -->
      <div class="lazy-cascader-search">
        <el-autocomplete
            :style="{ width: searchWidth || '100%' }"
            :popper-class="suggestionsPopperClass"
            v-if="filterable"
            class="inline-input"
            prefix-icon="el-icon-search"
            label="name"
            v-model="keyword"
            :fetch-suggestions="querySearch"
            :trigger-on-focus="false"
            placeholder="请输入"
            @select="handleSelect"
            @blur="isSearchEmpty = false"
        >
          <template slot-scope="{ item }">
            <div class="name" :class="isChecked(item[props.value])">
              {{ item[props.label].join(separator) }}
            </div>
          </template>
        </el-autocomplete>
        <div class="empty" v-show="isSearchEmpty">{{ searchEmptyText }}</div>
      </div>
      <!-- 搜索 -->
      <!-- 级联面板 -->
      <div class="lazy-cascader-panel">
        <el-cascader-panel
            :ref="`panel${props.type}`"
            v-model="current"
            :options="options"
            :props="currentProps"
            @change="change"
        ></el-cascader-panel>
      </div>
      <!-- 级联面板 -->
      <!--内容区域-->
      <div
          class="el-input__inner lazy-cascader-input"
          :class="disabled ? 'lazy-cascader-input-disabled' : ''"
          slot="reference"
      >
        <span class="lazy-cascader-placeholder" v-show="placeholderVisible">
          {{ placeholder }}
        </span>
        <div class="lazy-cascader-tags" v-if="props.multiple">
          <el-tag
              class="lazy-cascader-tag"
              type="info"
              disable-transitions
              v-for="(item, index) in labelArray"
              :key="index"
              closable
              @close="handleClose(item)"
          >
            <span> {{ item.label.join(separator) }}</span>
          </el-tag>
        </div>
        <div class="lazy-cascader-label" v-else>
          <el-tooltip
              placement="top-start"
              :content="labelObject.label.join(separator)"
          >
            <span>{{
                (props.orderbyDesc ? [...labelObject.label].reverse() : labelObject.label).join(separator)
              }}</span>
          </el-tooltip>
        </div>
      </div>
      <!--内容区域-->
    </el-popover>
    <!-- 可选状态 -->
  </div>
</template>
<script>
  export default {
    props: {
      value: {
        type: Array,
        default: () => {
          return [];
        }
      },
      separator: {
        type: String,
        default: ' > '
      },
      placeholder: {
        type: String,
        default: '请选择'
      },
      width: {
        type: String,
        default: '400px'
      },
      filterable: Boolean,
      disabled: Boolean,
      props: {
        type: Object,
        default: () => {
          return {};
        }
      },
      suggestionsPopperClass: {
        type: String,
        default: 'suggestions-popper-class'
      },
      searchWidth: {
        type: String
      },
      searchEmptyText: {
        type: String,
        default: '暂无数据'
      }
    },
    data() {
      return {
        singleHandleSelect: false, //用于解决插件延时bug
        isSearchEmpty: false,
        keyword: '',
        closeHandleSelect: 4000,
        options: [],
        current: [],
        labelObject: {label: [], value: []},
        labelArray: [],
        currentProps: {
          multiple: this.props.multiple,
          checkStrictly: this.props.checkStrictly,
          value: this.props.value,
          label: this.props.label,
          leaf: this.props.leaf,
          lazy: true,
          lazyLoad: this.lazyLoad
        }
      };
    },
    computed: {
      placeholderVisible() {
        if (this.current) {
          return this.current.length === 0;
        } else {
          return true;
        }
      }
    },
    watch: {
      async current() {
        await this.getLabelArray();
        // 异步完成,再通知change事件
        if(this.singleHandleSelect){
          this.change();
          this.singleHandleSelect = false;
        }
      },
      value(v) {
        this.current = v;
      },
      keyword() {
        this.isSearchEmpty = false;
      }
    },
    created() {
      this.initOptions();
    },
    methods: {
      //搜索是否选中
      isChecked(value) {
        //多选
        if (this.props.multiple) {
          let index = this.current.findIndex(item => {
            return item.join() === value.join();
          });
          if (index > -1) {
            return 'el-link el-link--primary';
          } else {
            return '';
          }
        } else {
          if (value.join() === this.current.join()) {
            return 'el-link el-link--primary';
          } else {
            return '';
          }
        }
      },
      //搜索
      querySearch(query, callback) {
        this.props.lazySearch(query, list => {
          // console.log('list', list);
          callback(list);
          if (!list || !list.length) this.isSearchEmpty = true;
        }, this.props.type);
      },
      //选中搜索下拉搜索项
      handleSelect(item) {
        if (this.props.multiple) {
          // console.log('multiple', item);
          let index = this.current.findIndex(obj => {
            return obj.join() === item[this.props.value].join();
          });
          if (index === -1) {
            this.$refs[`panel${this.props.type}`].clearCheckedNodes();
            this.current.push(item[this.props.value]);
            // setTimeout(() => {
              // this.change();
            // },  this.closeHandleSelect);
            this.singleHandleSelect = true;
          }
        } else {
          // console.log('single', item);
          //选中下拉选变更值
          // console.log(item,this.current);
          if (
              this.current == null ||
              item[this.props.value].join() !== this.current.join()
          ) {
            this.$refs[`panel${this.props.type}`].activePath = [];
            this.current = item[this.props.value];
            // setTimeout(() => {
              // this.change();
            // }, this.closeHandleSelect);
            this.singleHandleSelect = true;
          }
        }
        console.log('handleSelect');
        this.keyword = '';
      },
      //初始化数据
      async initOptions() {
        this.props.lazyLoad(0, list => {
          this.$set(this, 'options', list);
          if (this.props.multiple) {
            this.current = [...this.value];
          } else {
            this.current = this.value;
          }
        }, this.props.type);
      },
      async getLabelArray() {
        if (this.props.multiple) {
          let array = [];
          for (let i = 0; i < this.current.length; i++) {
            let obj = await this.getObject(this.current[i]);
            array.push(obj);
          }
          this.labelArray = array;
          this.$emit('input', this.current);
          if (!this.disabled) {
            this.$nextTick(() => {
              this.$refs.popover.updatePopper();
            });
          }
        } else {
          this.labelObject = await this.getObject(this.current || []);
          this.$emit('input', this.current);
        }
      },
      /**格式化id=>object */
      async getObject(id) {
        try {
          let options = this.options;
          let nameArray = [];
          for (let i = 0; i < id.length; i++) {
            let index = options.findIndex(item => {
              return item[this.props.value] === id[i];
            });
            nameArray.push(options[index][this.props.label]);
            if (i < id.length - 1 && options[index].children == undefined) {
              let list = new Promise(resolve => {
                this.props.lazyLoad(id[i], list => {
                  resolve(list);
                }, this.props.type);
              }, this.props.type);
              this.$set(options[index], 'children', await list);
              options = options[index].children;
            } else {
              options = options[index].children;
            }
          }
          return {value: id, label: nameArray};
        } catch (e) {
          this.current = [];
          return {value: [], label: []};
        }
      },
      //懒加载数据
      async lazyLoad(node, resolve) {
        console.log('lazyLoad');
        let current = this.current;
        if (this.props.multiple) {
          current = [...this.current];
        }
        if (node.root) {
          resolve();
        } else if (node.data[this.props.leaf]) {
          resolve();
        } else if (node.data.children) {
          if (this.props.multiple) {
            this.current = current;
          }
          resolve();
        } else {
          this.props.lazyLoad(node.value, list => {
            node.data.children = list;
            if (this.props.multiple) {
              this.current = current;
            }
            resolve(list);
          }, this.props.type);
        }
      },
      //删除多选值
      /**删除**/
      handleClose(item) {
        let index = this.current.findIndex(obj => {
          return obj.join() == item.value.join();
        });
        if (index > -1) {
          this.$refs[`panel${this.props.type}`].clearCheckedNodes();
          this.current.splice(index, 1);
          this.$emit('change', this.current);
        }
      },
      change() {
        console.log(88888888);
        this.$emit('change', this.current);
        this.$refs.popover.doClose();
      }
    }
  };
</script>
<style lang="less">
  .lazy-cascader {
    display: inline-block;
    width: 300px;

    .lazy-cascader-input {
      width: 100%;
      background: #fff;
      height: auto;
      min-height: 36px;
      padding: 5px;
      line-height: 1;
      cursor: pointer;

      > .lazy-cascader-placeholder {
        padding: 0 2px;
        line-height: 28px;
        color: #999;
        font-size: 14px;
      }

      > .lazy-cascader-label {
        padding: 0 2px;
        line-height: 28px;
        color: #606266;
        font-size: 14px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }

    .lazy-cascader-input-disabled {
      background-color: #f5f7fa;
      border-color: #e4e7ed;
      color: #c0c4cc;
      cursor: not-allowed;

      > .lazy-cascader-label {
        color: #c0c4cc;
      }

      > .lazy-cascader-placeholder {
        color: #c0c4cc;
      }
    }
  }

  .lazy-cascader-tag {
    display: inline-flex;
    align-items: center;
    max-width: 100%;
    margin: 2px;
    text-overflow: ellipsis;
    background: #f0f2f5;

    > span {
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    > .el-icon-close {
      -webkit-box-flex: 0;
      -ms-flex: none;
      flex: none;
      background-color: #c0c4cc;
      color: #fff;
    }
  }

  .lazy-cascader-panel {
    margin-top: 10px;
    display: inline-block;
  }

  .suggestions-popper-class {
    width: auto !important;
    min-width: 200px;
  }

  .lazy-cascader-search {
    .empty {
      width: calc(100% - 24px);
      box-sizing: border-box;
      background-color: #fff;
      color: #999;
      text-align: center;
      position: absolute;
      z-index: 999;
      padding: 12px 0;
      margin-top: 12px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

      &:before {
        content: "";
        position: absolute;
        top: -12px;
        left: 36px;
        width: 0;
        height: 0;
        border-left: 6px solid transparent;
        border-right: 6px solid transparent;
        border-top: 6px solid transparent;
        border-bottom: 6px solid #fff;
        filter: drop-shadow(0 -1px 2px rgba(0, 0, 0, .02));
      }
    }
  }
</style>

app.vue

<template>
  <div id="app">
     <lazy-cascader  ref="lzc" filterable  :props="lazyCascaderProps" @change="lazyCascaderChange" v-model="result"/>
      <el-button type="primary" @click="save">确 定</el-button>
  </div>
</template>
<script>
import LazyCascader from "./components/lazy-cascader.vue";
import { api } from "./utils/common";

export default {
  name: "App",
  components: {
    LazyCascader,
  },
  data: () => ({
    dialogVisible:false,
    result:[],
    lazyCascaderProps: {
      orderbyDesc: true,
      multiple: false,
      checkStrictly: false,
      value: "id",
      label: "name",
      type: 1,
      lazyLoad: async (nodeValue, resolve, type) => {
        const params = {
          type,
          organId: nodeValue,
          parentId: nodeValue,
        };
        const res = await api.getOrgAndPerson(params);
        resolve(res);
      },
      lazySearch: (queryString, callback, type) => {
        const params = {
          type,
          judgeName: queryString,
        };
        api.findOrgByJudgeName(params).then((data) => {
          callback(data);
        });
      },
    },
  }),
  methods: {
    save(){
      console.log(JSON.stringify(this.result));
      this.dialogVisible = false;
    },
    lazyCascaderChange(val){
      const node = this.$refs.lzc.$refs.panel1.getCheckedNodes()[0];
      const transferJudge = {};
      transferJudge.transferJudgeId = node?.data.id ?? '';
      transferJudge.transferJudgeDepartment = node?.parent?.data?.id ?? '';
      transferJudge.transferJudgeName = node?.data.name;
      console.log('transferJudge', transferJudge);
    }
  },
  mounted() {
   
  },
};
</script>

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.