El-cascader源码分析(上)未完结

1,132 阅读1分钟

主要内容

  1. cascader-node组件有一个handleExpand方法,该方法会调用inject进来的cascader-panel组件的handleExpand方法,该方法会在点击之后把node节点的children数组子节点push进去menus,然后用v-for对menu进行渲染,以此实现级联效果,同时有个if(!silent)判断,通过调用node.getValue拿到一个有node.value组成的数组,作为值显示在输入框
handleExpand(node, silent) {
  const { activePath } = this;
  const { level } = node;
  const path = activePath.slice(0, level - 1);
  const menus = this.menus.slice(0, level);

  if (!node.isLeaf) {
    path.push(node);
    menus.push(node.children);
  }

  this.activePath = path;
  this.menus = menus;

  if (!silent) {
    const pathValues = path.map(node => node.getValue());
    const activePathValues = activePath.map(node => node.getValue());
    if (!valueEquals(pathValues, activePathValues)) {
      this.$emit('active-item-change', pathValues); // Deprecated
      this.$emit('expand-change', pathValues);
    }
  }
},
  1. NODE.JS,如果没有children,则表示为叶子节点,isLeaf为true
// Node.js
get isLeaf() {
  const { data, loaded, hasChildren, children } = this;
  const { lazy, leaf: leafKey } = this.config;
  if (lazy) {
    const isLeaf = isDef(data[leafKey])
      ? data[leafKey]
      : (loaded ? !children.length : false);
    this.hasChildren = !isLeaf;
    return isLeaf;
  }
  return !hasChildren;
}

3.el-cascader组件选择之后里面的input显示值逻辑,主要是该组件的computePresentContent方法,该方法最终会调用conputePresentText方法并根据showAllLevels的props的Boolean值来判断是否根据分隔符限制还是只显示最终选择的那个,需要注意的是,这只是做一个显示的的操作而已,里面会调用node.getText方法,getText方法就是将传入的options里面的每一级的label的值push进一个数组里面,然后调用join方法用separator做为连接符号,之后显示在input上面

computePresentContent() {
  // nextTick is required, because checked nodes may not change right now
  this.$nextTick(() => {
    if (this.config.multiple) {
      this.computePresentTags();
      this.presentText = this.presentTags.length ? ' ' : null;
    } else {
      this.computePresentText();
    }
  });
},
computePresentText() {
  const { checkedValue, config } = this;
  if (!this.isEmptyValue(checkedValue)) {
    const node = this.panel.getNodeByValue(checkedValue);
    if (node && (config.checkStrictly || node.isLeaf)) {
      this.presentText = node.getText(this.showAllLevels, this.separator);
      return;
    }
  }
  this.presentText = null;
},