antd vue tree树形结构问题记录

1.节点数据显示上一个的数据
2.节点数据出现死循环
主要问题是,为了优化搜索性能,在请求接口的方法使用了节流函数,导致树形结构加载数据不能同步
处理方式是,将节流函数放到搜索方法

错误代码

<template>
  <div class="department-container">
    <div class="search">
      <a-input-search
        v-model="departName"
        placeholder="请输入搜索关键字"
        allowClear
        @search="haneleSearch"
        @change="haneleSearch"
      />
    </div>
    <div class="title flex row-middle row-between cursor" @click="haneleOther">
      <div :class="`other ${other ? 'active' : ''}`">
        其他成员
        <!-- <a-icon class="icon" type="question-circle" /> -->
      </div>
      <!-- <a-button type="primary" @click="handleSync">立即同步</a-button> -->
    </div>
    <div class="title flex row-middle row-between">
      <div>
        部门
        <!-- <a-icon class="icon" type="question-circle" /> -->
      </div>
      <!-- <a-button type="primary" @click="handleSync">立即同步</a-button> -->
    </div>
    <a-progress :percent="0" v-if="percent > 0"></a-progress>
    <div class="search-list" v-if="isSearch">
      <ul>
        <li
          v-for="(item, index) in searchData"
          :key="index"
          :class="searchKey == item.id ? 'active' : ''"
          @click="handleDepartClick(null, null, item, 'depart')"
        >
          <svg-icon icon-class="department"></svg-icon>{{ item.name }}
        </li>
      </ul>
    </div>
    <div v-show="!isSearch">
      <a-tree
        :load-data="onLoadData"
        :tree-data="treeData"
        :props="defaultProps"
        :show-icon="true"
        :check-strictly="true"
        :check-on-click-node="true"
        :default-expand-all="true"
        :expand-on-click-node="false"
        :selectedKeys="selectedKeys"
        @select="handleDepartClick"
      >
        <template slot="icon" slot-scope="item">
          <svg-icon
            v-if="item.depth == 0"
            icon-class="organization1"
          ></svg-icon>
          <svg-icon v-else icon-class="department"></svg-icon>
        </template>
        <template slot="custom" slot-scope="item">
          {{ item.name }}
        </template>
      </a-tree>
    </div>
  </div>
</template>
<script>
import { getUserPick, syncData } from "@/api/common";
import throttle from "lodash/throttle";
export default {
  name: "department",
  data() {
    return {
      treeData: [],
      searchData: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      percent: 0,
      departName: "",
      isSearch: false,
      selectedKeys: [],
      searchKey: "",
      other: false,
    };
  },
  created() {
    this.getDepartData();
  },
  methods: {
    async onLoadData(treeNode) {
      const that = this;
      return new Promise((resolve) => {
        // console.log(treeNode.dataRef)
        if (treeNode.dataRef.children) {
          resolve();
          return;
        }
        that.getDepartData(treeNode).then((res) => {
          treeNode.dataRef.children = res;
          that.treeData = [...that.treeData];
          resolve();
        });
      });
    },
  //错误示例
    getDepartData: throttle(async function () {
      let id = 0;
      const params = {};
      if (this.isSearch) {
        params.depart_name = this.departName;
        params.load = "search-department";
      } else {
        if (treeNode) {
          id = treeNode.dataRef.id;
        }
        params.department_id = id;
        params.load = "department";
      }
      const { data } = await getUserPick(params);
      if (treeNode) {
        return this.converData(data);
      }
      if (this.isSearch) {
        this.searchData = data;
        this.handleDepartClick(null, null, this.searchData[0]);
      } else {
        this.treeData = this.converData(data);
        if (!treeNode)
          this.handleDepartClick(null, null, this.treeData[0], "init");
      }
    }, 1000),
    converData(data) {
      data.forEach((item) => {
        item.isLeaf = !(parseInt(item.right) - parseInt(item.left) > 1);
        item.key = item.id;
        item.scopedSlots = {
          title: "custom",
          icon: "icon",
          switcherIcon: "switcherIcon",
        };
        if (item.children) {
          delete item.children;
        }
      });
      return data;
    },
    //   点击节点
    handleDepartClick(data, e, item, depart) {
      if (e || depart) {
        this.other = false;
        this.selectedKeys = [item ? item.id : e.node.dataRef.id];
        this.searchKey = item ? item.id : e.node.dataRef.id;
        this.$emit("change", item ? item : e.node.dataRef);
      }
    },
    haneleOther() {
      // -999 区分正常部门id, 表示为其他用户
      this.other = true;
      this.selectedKeys = [];
      this.$emit("change", { id: -999, name: "其他员工" });
    },
    haneleSearch(){
      this.isSearch = Boolean(this.departName);
      if (this.isSearch) {
        this.getDepartData();
      }
    },
    async handleSync() {
      let interval = setInterval(() => {
        this.percent = this.percent + 2;
        if (this.percent >= 80) clearInterval(interval);
      }, 300);
      this.hide = this.$message.loading("同步中...", 0);
      try {
        await syncData();
        setTimeout(() => {
          this.$message.success("操作成功");
          this.percent = 0;
        }, 2000);
        clearInterval(interval);
        setTimeout(this.hide, 0);
      } catch {
        this.percent = 0;
        clearInterval(interval);
        this.hide();
      }
      setTimeout(() => {
        clearInterval(interval);
        setTimeout(this.hide, 0);
      }, 600);
    },
  },
};
</script>
<style lang="less">
.department-container .ant-tree {
  font-size: 14px;
  .ant-tree-switcher i {
    font-size: @fontsize16 !important;
    color: @8B8B8B-color;
  }
}
</style>
<style lang="less" scoped>
.search {
  padding: 0 8px;
  /deep/.ant-input {
    .borderRadius(2px,2px,2px,2px);
  }
}
.search-list {
  li {
    cursor: pointer;
    line-height: 24px;
    margin: 8px 0;
    &.active {
      background-color: #bae7ff;
    }
    .svg-icon {
      margin-left: 10px;
      margin-right: 5px;
    }
  }
}
.other {
  &:hover {
    background-color: #e6f7ff;
  }
  &.active {
    background-color: #bae7ff;
  }
}
.title {
  margin-top: 15px;
  font-size: 14px;
  color: @text-color66;
  > div {
    padding: 2px 8px;
  }
  .icon {
    margin-left: 6px;
  }
  /deep/.ant-btn {
    background: @66B3FF-color;
    border: none;
    .borderRadius(2px,2px,2px,2px);
    padding: 0 8px;
    height: 30px;
  }
}
.department-container {
  max-height: 100%;
  height: calc(100vh - 128px);
  padding: 0 7px;
  box-sizing: border-box;
  overflow: hidden;
  overflow-y: auto;
  .is-horizontal {
    display: none;
  }
  /deep/.el-scrollbar__wrap {
    overflow-x: hidden;
    .el-scrollbar__view {
      padding: 0;
    }
  }
}
</style>

正确代码:

<template>
  <div class="department-container">
    <div class="search">
      <a-input-search
        v-model="departName"
        placeholder="请输入搜索关键字"
        allowClear
        @search="haneleSearch"
        @change="haneleSearch"
      />
    </div>
    <div class="title flex row-middle row-between cursor" @click="haneleOther">
      <div :class="`other ${other ? 'active' : ''}`">
        其他成员
        <!-- <a-icon class="icon" type="question-circle" /> -->
      </div>
      <!-- <a-button type="primary" @click="handleSync">立即同步</a-button> -->
    </div>
    <div class="title flex row-middle row-between">
      <div>
        部门
        <!-- <a-icon class="icon" type="question-circle" /> -->
      </div>
      <!-- <a-button type="primary" @click="handleSync">立即同步</a-button> -->
    </div>
    <a-progress :percent="0" v-if="percent > 0"></a-progress>
    <div class="search-list" v-if="isSearch">
      <ul>
        <li
          v-for="(item, index) in searchData"
          :key="index"
          :class="searchKey == item.id ? 'active' : ''"
          @click="handleDepartClick(null, null, item, 'depart')"
        >
          <svg-icon icon-class="department"></svg-icon>{{ item.name }}
        </li>
      </ul>
    </div>
    <div v-show="!isSearch">
      <a-tree
        :load-data="onLoadData"
        :tree-data="treeData"
        :props="defaultProps"
        :show-icon="true"
        :check-strictly="true"
        :check-on-click-node="true"
        :default-expand-all="true"
        :expand-on-click-node="false"
        :selectedKeys="selectedKeys"
        @select="handleDepartClick"
      >
        <template slot="icon" slot-scope="item">
          <svg-icon
            v-if="item.depth == 0"
            icon-class="organization1"
          ></svg-icon>
          <svg-icon v-else icon-class="department"></svg-icon>
        </template>
        <template slot="custom" slot-scope="item">
          {{ item.name }}
        </template>
      </a-tree>
    </div>
  </div>
</template>
<script>
import { getUserPick, syncData } from "@/api/common";
import throttle from "lodash/throttle";
export default {
  name: "department",
  data() {
    return {
      treeData: [],
      searchData: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      percent: 0,
      departName: "",
      isSearch: false,
      selectedKeys: [],
      searchKey: "",
      other: false,
    };
  },
  created() {
    this.getDepartData();
  },
  methods: {
    async onLoadData(treeNode) {
      const that = this;
      return new Promise((resolve) => {
        // console.log(treeNode.dataRef)
        if (treeNode.dataRef.children) {
          resolve();
          return;
        }
        that.getDepartData(treeNode).then((res) => {
          treeNode.dataRef.children = res;
          that.treeData = [...that.treeData];
          resolve();
        });
      });
    },
   //正确示例
    async getDepartData(treeNode) {
      let id = 0;
      const params = {};
      if (this.isSearch) {
        params.depart_name = this.departName;
        params.load = "search-department";
      } else {
        if (treeNode) {
          id = treeNode.dataRef.id;
        }
        params.department_id = id;
        params.load = "department";
      }
      const { data } = await getUserPick(params);
      if (treeNode) {
        return this.converData(data);
      }
      if (this.isSearch) {
        this.searchData = data;
        this.handleDepartClick(null, null, this.searchData[0]);
      } else {
        this.treeData = this.converData(data);
        if (!treeNode)
          this.handleDepartClick(null, null, this.treeData[0], "init");
      }
    },
    converData(data) {
      data.forEach((item) => {
        item.isLeaf = !(parseInt(item.right) - parseInt(item.left) > 1);
        item.key = item.id;
        item.scopedSlots = {
          title: "custom",
          icon: "icon",
          switcherIcon: "switcherIcon",
        };
        if (item.children) {
          delete item.children;
        }
      });
      return data;
    },
    //   点击节点
    handleDepartClick(data, e, item, depart) {
      if (e || depart) {
        this.other = false;
        this.selectedKeys = [item ? item.id : e.node.dataRef.id];
        this.searchKey = item ? item.id : e.node.dataRef.id;
        this.$emit("change", item ? item : e.node.dataRef);
      }
    },
    haneleOther() {
      // -999 区分正常部门id, 表示为其他用户
      this.other = true;
      this.selectedKeys = [];
      this.$emit("change", { id: -999, name: "其他员工" });
    },
    haneleSearch: throttle(function () {
      this.isSearch = Boolean(this.departName);
      if (this.isSearch) {
        this.getDepartData();
      }
    }, 1000),
    async handleSync() {
      let interval = setInterval(() => {
        this.percent = this.percent + 2;
        if (this.percent >= 80) clearInterval(interval);
      }, 300);
      this.hide = this.$message.loading("同步中...", 0);
      try {
        await syncData();
        setTimeout(() => {
          this.$message.success("操作成功");
          this.percent = 0;
        }, 2000);
        clearInterval(interval);
        setTimeout(this.hide, 0);
      } catch {
        this.percent = 0;
        clearInterval(interval);
        this.hide();
      }
      setTimeout(() => {
        clearInterval(interval);
        setTimeout(this.hide, 0);
      }, 600);
    },
  },
};
</script>
<style lang="less">
.department-container .ant-tree {
  font-size: 14px;
  .ant-tree-switcher i {
    font-size: @fontsize16 !important;
    color: @8B8B8B-color;
  }
}
</style>
<style lang="less" scoped>
.search {
  padding: 0 8px;
  /deep/.ant-input {
    .borderRadius(2px,2px,2px,2px);
  }
}
.search-list {
  li {
    cursor: pointer;
    line-height: 24px;
    margin: 8px 0;
    &.active {
      background-color: #bae7ff;
    }
    .svg-icon {
      margin-left: 10px;
      margin-right: 5px;
    }
  }
}
.other {
  &:hover {
    background-color: #e6f7ff;
  }
  &.active {
    background-color: #bae7ff;
  }
}
.title {
  margin-top: 15px;
  font-size: 14px;
  color: @text-color66;
  > div {
    padding: 2px 8px;
  }
  .icon {
    margin-left: 6px;
  }
  /deep/.ant-btn {
    background: @66B3FF-color;
    border: none;
    .borderRadius(2px,2px,2px,2px);
    padding: 0 8px;
    height: 30px;
  }
}
.department-container {
  max-height: 100%;
  height: calc(100vh - 128px);
  padding: 0 7px;
  box-sizing: border-box;
  overflow: hidden;
  overflow-y: auto;
  .is-horizontal {
    display: none;
  }
  /deep/.el-scrollbar__wrap {
    overflow-x: hidden;
    .el-scrollbar__view {
      padding: 0;
    }
  }
}
</style>

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 229,517评论 6 539
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 99,087评论 3 423
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 177,521评论 0 382
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 63,493评论 1 316
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 72,207评论 6 410
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 55,603评论 1 325
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 43,624评论 3 444
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 42,813评论 0 289
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 49,364评论 1 335
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 41,110评论 3 356
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 43,305评论 1 371
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 38,874评论 5 362
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 44,532评论 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 34,953评论 0 28
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 36,209评论 1 291
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 52,033评论 3 396
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 48,268评论 2 375

推荐阅读更多精彩内容