elementui多选tree table树表格 组件化使用

使用elementui 中table实现多选树表格,可多选,可全选,
本文将原来的进行了更改,适配自己的需求,查看原demo请查看
https://blog.csdn.net/qq_32442967/article/details/103068920

直接下载地址:https://download.csdn.net/download/qq_32442967/12015371

注:element-ui@2.5.4版本完美支持,在新版本elementUI中,默认不全展开时,会出现问题,在默认全部展开时不影响效果。

样式:
在这里插入图片描述


courseProgress.vue

<template>
  <div>
    <tree-table ref="tree1"
                :data="coursewareList"
                :columns="columns"
                :primary_fld="'id'"
                :expand-all="expandAll"
                :parent_fld="'parent_id'"
                :select_fld="'false'"
                @replayStudy="replayStudy">
      <el-table-column label="课件进度" min-width="150" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.progress}}</span>
        </template>
      </el-table-column>
    </tree-table>
  </div>
</template>

<script>

import treeTable from './components/treeTable'

export default {
  name: 'courseProgress',
  components: {
    treeTable
  },
  data () {
    
    return {
      expandAll: true,
      columns: [{value: 'itemName', text: '章节', minWidth: '300'}],
      coursewareList: [{
        id: '1',
        parent_id: '',
        itemName: '第一章',
        progress: '86%',
        comment: '',
        type: 'chapter'
      },
      {
        id: '2',
        parent_id: '',
        itemName: '第二章',
        progress: '86%',
        type: 'chapter'
      },
      {
        id: '3',
        parent_id: '1',
        itemName: '第1节',
        progress: '86%',
        type: 'node'
      },
      {
        id: '4',
        parent_id: '2',
        itemName: '第2节',
        progress: '86%',
        type: 'node'
      },
      {
        id: '5',
        parent_id: '1',
        itemName: '第2节',
        progress: '100%',
        type: 'node'
      },
      {
        id: '9',
        parent_id: '3',
        itemName: '第1考点',
        progress: '100%',
        type: 'point'
      },
      {
        id: '10',
        parent_id: '3',
        itemName: '第2考点',
        progress: '100%',
        type: 'point'
      },
      {
        id: '11',
        parent_id: '5',
        itemName: '第一考点',
        progress: '100%',
        type: 'point'
      },
      {
        id: '12',
        parent_id: '4',
        itemName: '第一考点',
        progress: '100%',
        type: 'point'
      },
      {
        id: '9',
        parent_id: '',
        itemName: '综合学习',
        progress: '100%',
        type: 'point'
      }]
    }
  },
  methods: {
    
  }
}
</script>

<style scoped>

</style>

treeTable.vue

<template>
  <div>
    <el-table :data="formatData" :row-style="showRow" v-bind="$attrs" v-on="$listeners">,
      <template v-if="select_fld">
        <el-table-column width="50" align="center">,
          <template slot="header" slot-scope="scope">
            <el-checkbox v-model="chooseall" @change="setchildtobeselect(formatData,$event)"/>
          </template>
          <template slot-scope="scope">
            <el-checkbox v-model="scope.row[select_fld]" @change="toselect(scope.row)"></el-checkbox>
          </template>
        </el-table-column>
      </template>

      <el-table-column v-if="columns.length===0">
        <template slot-scope="scope">
          <span v-for="space in scope.row._level" :key="space" class="ms-tree-space"></span>
          <span v-if="iconShow(0,scope)" class="tree-ctrl" @click="toggleExpanded(scope.$index)">
            <i v-if="!scope.row._expanded" class="el-icon-plus"></i>
            <i v-else class="el-icon-minus"></i></span>
          {{ scope.$index }}
        </template>
      </el-table-column>
      <!--自定义树节点显示的列值-->
      <el-table-column v-for="(column, index) in columns" v-else :key="column.value" :label="column.text" :width="column.width" :min-width="column.minWidth">
        <template slot-scope="scope">
          <!-- Todo -->
          <span v-for="space in scope.row._level" v-if="index === 0" :key="space" class="ms-tree-space"></span>
          <el-button size="mini" style="color: #17CAAA" v-if="scope.row.type === 'point'">替学</el-button>
          <span v-if="iconShow(index,scope)" class="tree-ctrl" @click="toggleExpanded(scope.$index)">
            <i v-if="!scope.row._expanded" class="el-icon-caret-right"></i>
            <i v-else class="el-icon-caret-bottom"></i></span>
          {{ scope.row[column.value] }}
        </template>
      </el-table-column>
      <slot/>
    </el-table>
  </div>
</template>

<script>
export default {
  name: 'treeTable',
  data () {
    return {
      // chooseson: true, // 全选
      key: true, // 单个点击直到全部选中
      // 当前全选状态
      chooseall: false
    }
  },
  props: {
    /* eslint-disable */
    data: {
      type: [Array, Object],
      required: true
    },
    columns: {
      type: Array,
      default: () => []
    },
    evalFunc: Function,
    evalArgs: Array,
    expandAll: {
      type: Boolean,
      default: false
    },
    select_fld: {
      type: String,
      //default: "id"
      default: ""
    },
    //-----------------------------------------
    // 如果数据源是靠字父级字段来表示树的话,primary_fld和parent_fld必须同时传入,并指定root_value
    primary_fld: {
      type: String,
      default: "id",
      required: true
    },
    parent_fld: {
      type: String,
      //default: "parent_id"
      default: ""
    },
    // 根级节点值
    root_value: {
      type: [String, Number],
      //default: "parent_id"
      default: ""
    },
    // 可选,子节点数的字段,如果含有此字段,将会加快加载速度
    child_count_fld: {
      type: String,
      //default: "childCount"
      default: ""
    }
  },
  computed: {
    // 格式化数据源
    formatData: function () {
      let result = [];
      let tmp;
      let func = this.evalFunc;

      if (this.is_source_table) {
        // 数据源是一个表格数组,依靠关键字段和父级id组成关系
        tmp = 0;
        func = this.tableToTree;
      } else if (Array.isArray(this.data)) {
        tmp = this.data;
      } else {
        tmp = [this.data];
      }

      const args = this.evalArgs ? [result, tmp, this.expandAll].concat(this.evalArgs) : [result, tmp, this.expandAll];
      //return func.apply(null, args);
      func.apply(null, args);
      return result;
    },
    // 判断数据源是否使用父级字段来表示的二维的表格树
    is_source_table: function () {
      return this.primary_fld && this.parent_fld;
    }
  },
  methods: {
    //代替原来的 treeToArray函数
    tableToTree: function (tResult, tStartRecno, expandAll, parent, level, item) {

      const that = this;
      let parent_value = that.root_value;
      let _level = 1;
      let record = null;
      let child = null;
      const marLTemp = []
      let tmp = []

      if (parent) {
        parent_value = parent[that.primary_fld];
        _level = level;
      }


      //Array.from(data).forEach(function(record) {
      for (let i = tStartRecno, count = that.data.length; i < count; i++) {
        record = that.data[i];

        if (record[that.parent_fld] !== parent_value) {
          continue;
        }
        if (record._expanded === undefined) {
          this.$set(record, '_expanded', expandAll)
        }

        this.$set(record, '_level', _level)
        // 如果有父元素
        if (parent) {
          this.$set(record, 'parent', parent)
          // 如果父元素有偏移量,需要计算在this的偏移量中
          // 偏移量还与前面同级元素有关,需要加上前面所有元素的长度和
          if (!marLTemp[_level]) {
            marLTemp[_level] = 0
          }
          this.$set(record, '_marginLeft', marLTemp[_level] + parent._marginLeft)
          this.$set(record, '_width', record[item] / parent[item] * parent._width)
          // 在本次计算过偏移量后加上自己长度,以供下一个元素使用
          marLTemp[_level] += record._width
        } else {
          // 如果为根
          // 初始化偏移量存储map
          marLTemp[record[that.primary_fld]] = []
          // map中是一个数组,存储的是每级的长度和
          // 初始情况下为0
          marLTemp[record[that.primary_fld]][_level] = 0
          this.$set(record, '_marginLeft', 0)
          this.$set(record, '_width', 1)
        }
        tmp.push(record)
        tResult.push(record);
        // 表含有表示子节点数量的字段
        let is_seek_child = 1;
        if (that.child_count_fld) {
          is_seek_child = record[that.child_count_fld];
        }
        if (is_seek_child) {
          const next_recno = i + 1;
          const next_level = _level + 1;

          child = that.tableToTree(tResult, next_recno, expandAll, record, next_level, item);

          if (child.length > 0) {
            //tmp = tmp.concat(child);
            if (!record.child) {
              this.$set(record, 'child', child);
            }
          }

        }
      }
      //})
      return tmp
    },
    showRow: function (row) {
      const show = row.row.parent ?
        row.row.parent._expanded && row.row.parent._show :
        true;
      row.row._show = show;
      return show ?
        "animation:treeTableShow 1s;-webkit-animation:treeTableShow 1s;" :
        "display:none;";
    },
    // 切换下级是否展开
    toggleExpanded: function (trIndex) {
      const record = this.formatData[trIndex];
      record._expanded = !record._expanded;
    },
    // 图标显示
    iconShow(index, tScope) {
      const record = tScope.row;
      //console.info(tScope.$index);
      return index === 0 && record.child && record.child.length > 0;


    },
    //功能函数:选中部分子集
    setchildtobeselect(arr, key) {
      const that = this;
      arr.forEach((v, i) => {
        //v.checks = key;
        v[that.select_fld] = key;
        // v._expanded = key;//选中后展开子项
        if (v.child) {
          this.setchildtobeselect(v.child, v[that.select_fld]);
        }
      });
    },
    //是否所有的都被选中
    isallchecked(arr) {
      const that = this;
      arr.forEach((v, i) => {
        if (!v[that.select_fld]) {
          // 根据评论中建议进行修改-深度渲染。在展开关闭之后,点击 checkbox 会不渲染
          // this.key = false;
          this.$set(this, "key", false);
        }
        if (v.child) {
          this.isallchecked(v.child);
        }
      });
    },

    // 节点下的子节点,全部都没有被选中或子节点个数为0时返回true,否则返回false
    is_all_false(tNode) {
      const that = this;
      let result = true;
      if (!Array.isArray(tNode.child)) {
        return result;
      }
      tNode.child.forEach((v, index) => {
        // 只要有一个兄弟是true,终止递归
        if (v[that.select_fld]) {
          result = false;
          return result; //终止此次循环,减少循环次数
        }
      });
      return result;
    },
    // 如果节点为被选状态,通过检查子节点是否有被选中,否则修正它
    refresh_node_select(tNode) {
      const that = this;
      let node = tNode;
      while (true) {
        // 选中?
        if (node[that.select_fld]) {
          if (that.is_all_false(node)) {
            node[that.select_fld] = false;
          } else {
            break;
          }
        }
        if (node["parent"]) {
          node = node["parent"];
        } else {
          break;
        }

      }
    },

    //某个复选框被点击时
    toselect(row) {
      const that = this;
      let node = null;
      // row._expanded = row.checks;//选中后是否展开
      //1、若有子集先让子选中
      if (row.child) {
        this.setchildtobeselect(row.child, row[that.select_fld]);
      }
      //2、然后判断是否全选中
      this.key = true; //重置为true,防止上次已经是false的状态  |半选状态is-indeterminate
      this.isallchecked(this.formatData);
      //3、设置多选框的状态
      if (!row[that.select_fld]) {
        //this.setparentfalse(this.formatData, row[that.primary_fld], row._level); //设置父级选中的状态为false
        if (row.parent) {
          that.refresh_node_select(row.parent);
        }
        //设置全选框的状态
        that.chooseall = false;
        //document.getElementById("chooseall").checked = false;
      } else {
        node = row;
        while (node["parent"]) {
          node = node["parent"];
          if (!node[that.select_fld]) {
            node[that.select_fld] = true;
          }
        }
        //this.setparenttrue(this.formatData, row[that.primary_fld], row._level); //设置父级选中的状态为true
      }
      if (this.key) {
        that.chooseall = true;
        //document.getElementById("chooseall").checked = true; //设置全选框的状态
      }
    },
    replayStudy (row) {
      this.$emit('replayStudy', row)
    }
  },
  mounted() {
    this.$nextTick(() => {
      var that = this;
      //const all = document.getElementById("chooseall");

    });
  },
}
</script>

<style scoped>
  @keyframes treeTableShow {
    from {
      opacity: 0;
    }
    to {
      opacity: 1;
    }
  }

  @-webkit-keyframes treeTableShow {
    from {
      opacity: 0;
    }
    to {
      opacity: 1;
    }
  }
  .ms-tree-space {
    position: relative;
    top: 1px;
    display: inline-block;
    font-style: normal;
    font-weight: 400;
    line-height: 1;
    width: 18px;
    height: 14px;
  }
  .ms-tree-space::before {
    content: "";
  }
  .processContainer {
    width: 100%;
    height: 100%;
  }
  table td {
    line-height: 26px;
  }
  .tree-ctrl {
    position: relative;
    cursor: pointer;
    /*color: #2196f3;*/
    margin-left: -18px;
  }
</style>

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值