Commit 07d361f4983fb2f0d237ca4602f8bd54f5e54f2e

Authored by luowenfeng
1 parent e2a6530a

feature(uniapp分类): 分类列表以及商品加载

Showing 1 changed file with 59 additions and 0 deletions
yudao-ui-app/utils/tree.js 0 → 100644
  1 +/**
  2 + * 构造树型结构数据
  3 + * @param {*} data 数据源
  4 + * @param {*} id id字段 默认 'id'
  5 + * @param {*} parentId 父节点字段 默认 'parentId'
  6 + * @param {*} children 孩子节点字段 默认 'children'
  7 + * @param {*} rootId 根Id 默认 0
  8 + */
  9 +export function handleTree(data, id, parentId, children, rootId) {
  10 + id = id || 'id'
  11 + parentId = parentId || 'parentId'
  12 + children = children || 'children'
  13 + rootId = rootId || Math.min.apply(Math, data.map(item => {
  14 + return item[parentId]
  15 + })) || 0
  16 + //对源数据深度克隆
  17 + const cloneData = JSON.parse(JSON.stringify(data))
  18 + //循环所有项
  19 + const treeData = cloneData.filter(father => {
  20 + let branchArr = cloneData.filter(child => {
  21 + //返回每一项的子级数组
  22 + return father[id] === child[parentId]
  23 + });
  24 + branchArr.length > 0 ? father.children = branchArr : '';
  25 + //返回第一层
  26 + return father[parentId] === rootId;
  27 + });
  28 + return treeData !== '' ? treeData : data;
  29 +}
  30 +
  31 +/**
  32 + * 树形结构进行删除深度不够的分支
  33 + * 目前只删除了不够三层的分支
  34 + * 对于高于三层的部分目前不做处理
  35 + * todo 暴力遍历,可用递归修改
  36 + * @param {*} data 树形结构
  37 + */
  38 +export function convertTree(data) {
  39 + //对源数据深度克隆
  40 + const cloneData = JSON.parse(JSON.stringify(data))
  41 + // 遍历克隆数据,对源数据进行删除操作
  42 + for (let first = 0; first < cloneData.length; first++) {
  43 + for (let second = 0; second < cloneData[first].children.length; second++) {
  44 + for (let three = 0; three < cloneData[first].children[second].children.length; three++) {
  45 + if (data[first].children[second].children[three].children == undefined ||
  46 + data[first].children[second].children[three].children === 0) {
  47 + data[first].children[second].children.splice(second, 1);
  48 + }
  49 + }
  50 + if (data[first].children[second].children == undefined || data[first].children[second].children === 0) {
  51 + data[first].children.splice(second, 1);
  52 + }
  53 + }
  54 + if (data[first].children == undefined || data[first].children.length === 0) {
  55 + data.splice(first, 1);
  56 + }
  57 + }
  58 + return data;
  59 +}
... ...