Vue + Element UI表格(樹形數(shù)據(jù)與懶加載)增、刪迈勋、改炬灭、查以及節(jié)點不刷新解決辦法

小白入門請多關(guān)照.如有問題,還望指點!
如果覺得不錯請支持一下!


image.png

核心代碼

更新樹狀節(jié)點
注意修改tableRefName

    updateTableTree(pid, nodes) {
      //更新節(jié)點數(shù)據(jù)
      //pid為父級id,nodes為修改后的子集內(nèi)容
      //以下面數(shù)據(jù)結(jié)構(gòu)舉例
      //pid=3  子集為id等于3的children數(shù)據(jù)
      this.$set(this.$refs.tableRefName.store.states.lazyTreeNodeMap,pid, nodes );
    },
    refTable() {
     /**
      *作用:更新樹狀節(jié)點
      * 因樹狀原因需更新外層
      *所以遞歸更新所有節(jié)點
      */
      let _this = this;
      function dg(data) {
        for (let i in data) {
          if (data[i].children) {
            _this.updateTableTree(data[i].id, data[i].children);
            dg(data[i].children);
          }
        }
      }
      dg(this.tableData);
    }

數(shù)據(jù)結(jié)構(gòu)

        sourceData: [{
          id: 3,
          date: '2016-05-01',
          name: '王小虎',
          address: '上海市普陀區(qū)金沙江路 1519 弄',
          pid: null,
          children: [{
              id: 31,
              date: '2016-05-01',
              name: '王小虎',
              address: '上海市普陀區(qū)金沙江路 1520 弄',
              pid: 3
            }, {
              id: 32,
              date: '2016-05-01',
              name: '王小虎',
              address: '上海市普陀區(qū)金沙江路 1521 弄',
              pid: 3
          }]
        }, {
          id: 4,
          date: '2016-05-03',
          name: '王小虎',
          address: '上海市普陀區(qū)金沙江路 1516 弄'
        }],

全部源碼

增刪改查的地方已修改為相應(yīng)的注釋

<template>
  <div style="width:100%;height:100%">
    <div class="cd-tool">
      <el-input size="mini" style="width:220px" v-model="searchValue" placeholder="請輸入地址關(guān)鍵字"></el-input>
      <el-button type size="mini" @click="search">搜索</el-button>
      <el-button type size="mini" @click="enableSel=!enableSel">{{enableSel?'關(guān)閉':'啟用'}}選擇</el-button>
      <el-button type size="mini" @click="relDict">關(guān)聯(lián)字典</el-button>
      <el-button type size="mini" @click="addTool">新增</el-button>
      <el-button type size="mini" @click="batchEdit">批量編輯</el-button>
      <el-button type size="mini" @click="batchDel">批量刪除</el-button>
      <el-button type size="mini" @click="saveTbale">保存</el-button>
    </div>
    <el-table
      :data="tableData"
      style="width: 100%"
      row-key="id"
      border
      stripe
      size="mini"
      class="data-table"
      ref="cimsDictTable"
      tooltip-effect="dark"
      :height="tableMaxHeight"
      @selection-change="handleSelectionChange"
      @select="select"
      @select-all="selectAll"
      header-row-class-name="data-table-header"
      lazy
      :show-overflow-tooltip="true"
      :load="load"
      :tree-props="{children:'children'}"
    >
      <el-table-column v-if="enableSel" type="selection" width="55"></el-table-column>
      <el-table-column label="日期">
        <template slot-scope="scope">
          <el-input v-model="scope.row.date" placeholder="請輸入字典名稱" v-if="scope.row.edit"></el-input>
          <span v-else>{{scope.row.date}}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名">
        <template slot-scope="scope">
          <el-input v-model="scope.row.name" placeholder="請輸入字典名稱" v-if="scope.row.edit"></el-input>
          <span v-else>{{scope.row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column label="地址">
        <template slot-scope="scope">
          <el-input v-model="scope.row.address" placeholder="請?zhí)顚憘渥? v-if="scope.row.edit"></el-input>
          <span v-else>{{scope.row.address}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="editRow(scope.row,scope.$index)">編輯</el-button>
          <el-button type="text" size="mini" @click="delRow(scope.row,scope.$index)">刪除</el-button>
          <el-button type="text" size="mini" @click="addRow(scope.row,scope.$index)">新增</el-button>
          <!-- <el-button type="text" size="mini" @click="upRow(scope,scope.row,scope.$index)">上移</el-button>
          <el-button type="text" size="mini" @click="downRow(scope.row,scope.$index)">下移</el-button>-->
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="菜單選擇" :visible.sync="dialogVisibleMenu" width="30%" :before-close="Menuclose">
      <el-tree
        class="filter-tree"
        :data="menuSource"
        node-key="id"
        :props="defaultProps"
        :default-expand-all="false"
        :expand-on-click-node="false"
        ref="tree"
        @node-click="onMenuSl"
      >
        <span class="custom-tree-node" slot-scope="{ node}">
          <span>{{ node.label }}</span>
        </span>
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleMenu = false">取 消</el-button>
        <el-button type="primary" @click="cnfAsMenu">確 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
function filterNodes(nodes, query, filterName) {
  // 條件就是節(jié)點的filterName過濾關(guān)鍵字
  let predicate = function (node) {
    if (node[filterName].indexOf(query) > -1) {
      return true;
    } else {
      return false;
    }
  };
  if (!(nodes && nodes.length)) {
    return [];
  }
  let newChildren = [];
  for (let node of nodes) {
    let subs = filterNodes(node.children, query, filterName);

    if (predicate(node)) {
      newChildren.push(node);
    } else if (subs && subs.length) {
      node.children = subs;
      newChildren.push(node);
    }
  }
  return newChildren.length ? newChildren : [];
}

export default {
  name: "tree-table",
  data() {
    return {
      dialogVisibleMenu: false,
      ref: "cimsDictTable",
      tableMaxHeight: 400,
      enableSel: false,
      tableData: [],
      cimsDictTable: [],
      searchSource: [],
      searchValue: "",
      menuSource: [],
      defaultProps: {
        children: "children",
        label: "name",
      }, //菜單節(jié)點
      sourceData: [
        {
          id: 1,
          date: "2016-05-02",
          name: "王小虎",
          address: "上海市普陀區(qū)金沙江路 1518 弄",
          pid: null,
        },
        {
          id: 2,
          date: "2016-05-04",
          name: "王小虎",
          address: "上海市普陀區(qū)金沙江路 1517 弄",
          pid: null,
        },
        {
          id: 3,
          date: "2016-05-01",
          name: "王小虎",
          address: "上海市普陀區(qū)金沙江路 1519 弄",
          pid: null,
          children: [
            {
              id: 31,
              date: "2016-05-01",
              name: "王小虎",
              address: "上海市普陀區(qū)金沙江路 1520 弄",
              pid: 3,
            },
            {
              id: 32,
              date: "2016-05-01",
              name: "王小虎",
              address: "上海市普陀區(qū)金沙江路 1521 弄",
              pid: 3,
            },
          ],
        },
        {
          id: 4,
          date: "2016-05-03",
          name: "王小虎",
          address: "上海市普陀區(qū)金沙江路 1516 弄",
        },
      ],
    };
  },
  methods: {
    addTool() {
      let addrow = this.setRowData();
      this.tableData.push(addrow);
    },
    onMenuSl(obj, node, data) {
      this.id = obj.id;
    },
    cnfAsMenu() {
      if (this.id == null) {
        this.$message({
          message: "請先選擇關(guān)聯(lián)菜單! ",
          type: "warning",
        });
      } else {
        let arr = this.getSelectedList();
        let p = arr.map((m) => m.id);
        //關(guān)聯(lián)字典接口
        this.$message({
          message: "關(guān)聯(lián)成功! ",
          type: "success",
        });
        this.dialogVisibleMenu = false;
        this.initData();
        this.id = null;
      }
    },
    Menuclose() {
      this.dialogVisibleMenu = false;
    },
    search() {
      this.tableData = filterNodes(
        this.searchSource,
        this.searchValue,
        "address"
      );
      this.refTable();
    },
    setRowData(pid) {
      return {
        id: new Date().valueOf(),
        name: "",
        pid: pid ? pid : null,
        address: "",
        edit: true,
        add: true,
      };
    },
    relDict() {
      //關(guān)聯(lián)字典
      if (!this.checkSelected(this.cimsDictTable, "至少選擇一項")) {
        return;
      }
      //模仿數(shù)據(jù)請求接口
      let res = this.sourceData;
      this.menuSource = JSON.parse(JSON.stringify(res));
      this.dialogVisibleMenu = true;
    },
    tableRules(list) {
      /**
       * 驗證規(guī)則
       * name不為空
       */
      for (let i in list) {
        if (list[i].name) {
          return false;
        }
      }
      return true;
    },
    saveTbale() {
      //保存
      let saveList = [];
      let saveTableData = JSON.parse(JSON.stringify(this.tableData));
      function dg(saveTableData) {
        for (let i in saveTableData) {
          if (saveTableData[i].edit) {
            //設(shè)置序號
            saveTableData[i].cdOrderNum = parseInt(i) + 1;
            //2.重置新增數(shù)據(jù)的id為null
            if (saveTableData[i].add) {
              saveTableData[i].id = null;
            }
            //3.保存編輯的數(shù)據(jù)
            saveList.push(saveTableData[i]);
          }
          if (saveTableData[i].children) {
            dg(saveTableData[i].children);
          }
        }
      }
      dg(saveTableData);
      if (!this.checkSelected(saveList, "至少編輯一項")) {
        return;
      }
      if (this.tableRules(saveList)) {
        this.$message.error("編輯項中存在空數(shù)據(jù),請?zhí)顚懟蛘邉h除");
        return;
      }
      this.$confirm(`操作確認,是否繼續(xù)?`, "提示", {
        confirmButtonText: "確定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //批量保存與更新接口
          this.$message({
            message: "操作成功! ",
            type: "success",
          });
          this.initData();
        })
        .catch(() => {});
    },
    //表格選擇操作方法
    // 手動勾選數(shù)據(jù)行
    select(selection, row) {
      // 判斷當(dāng)前行是否選中
      // 不需要判斷 id, 因為引用地址相同
      const selected = selection.some((item) => item === row);
      // 處理所有子級
      this.selectChildren(row, selected);
    },
    selectAll(selection) {
      /*
       * 這里引用別人的代碼:
       * selectAll 只有兩種狀態(tài): 全選和全不選
       * 所以我們只需要判斷一種狀態(tài)即可
       * 而且也不需要判斷 id, 因為 selection 和 this.data 中對象引用地址是相同的
       */
      // tableData 第一層只要有在 selection 里面就是全選
      const isSelect = this.tableData.some((item) => selection.includes(item));
      if (isSelect) {
        selection.forEach((item) => {
          this.selectChildren(item, isSelect);
        });
      } else {
        this.tableData.forEach((item) => {
          this.selectChildren(item, isSelect);
        });
      }
    },
    selectChildren(row, selected) {
      if (row["children"] && Array.isArray(row["children"])) {
        row["children"].forEach((item) => {
          this.toggleSelection(item, selected);
          this.selectChildren(item, selected);
        });
      }
    },
    selectionChange(selection) {
      this.debounce(this.tableSelectChange, 100, selection);
    },
    toggleSelection(row, select) {
      row &&
        this.$nextTick(() => {
          this.$refs[this.ref] &&
            this.$refs[this.ref].toggleRowSelection(row, select);
        });
    },
    cancelAll() {
      this.$refs[this.ref] && this.$refs[this.ref].clearSelection();
    },
    // 防抖
    debounce(fun, wait, params) {
      clearTimeout(this.timeout);
      this.timeout = setTimeout(fun, wait, params);
    },
    getSelectedList() {
      //獲取選中數(shù)據(jù)源
      let list = JSON.parse(JSON.stringify(this.cimsDictTable));
      list.forEach((e) => (e.children = null));
      return list;
    },
    checkSelected(data, mange) {
      //批量操作檢查
      let v = data.length > 0;
      if (!v) {
        this.$message({
          type: "warning",
          message: mange,
        });
      }
      return v;
    },
    batchEdit() {
      //批量編輯
      if (!this.checkSelected(this.cimsDictTable, "至少選擇一項")) {
        return;
      }
      for (let i in this.cimsDictTable) {
        this.$set(this.cimsDictTable[i], "edit", true);
      }
    },
    batchDel() {
      //批量刪除
      if (!this.checkSelected(this.cimsDictTable, "至少選擇一項")) {
        return;
      }
      let arr = this.getSelectedList();
      this.$confirm(`刪除選中的${arr.length}項目數(shù)據(jù)?`, "提示", {
        confirmButtonText: "確定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let p = [];
          arr.forEach((d) => {
            if (!d.add) {
              p.push(d.id);
            }
          });
          //刪除接口
          //todo:需判斷2種狀態(tài)提示 前端刪除 和 需要傳回后端
          this.initData();
        })
        .catch(() => {});
    },
    addRow(row, index) {
      if (!row.add) {
        //新增行數(shù)據(jù)
        let addrow = this.setRowData(row.id);
        //新增
        if (row.children) {
          row.children.push(addrow);
        } else {
          //添加數(shù)據(jù)
          this.$set(row, "children", [addrow]);
        }
        //展開行
        this.$nextTick(() => {
          //更新后打開節(jié)點
          this.$refs.cimsDictTable.toggleRowExpansion(row, true);
          //刷新樹
          this.refTable();
        });
      } else {
        this.$message({
          message: "請保存后再繼續(xù)添加子節(jié)點!",
          type: "warning",
        });
      }
    },
    updateTableTree(pid, nodes) {
      //更新需要先更新上級節(jié)點
      this.$set(
        this.$refs.cimsDictTable.store.states.lazyTreeNodeMap,
        pid,
        nodes
      );
    },
    refTable() {
      let _this = this;
      function dg(data) {
        for (let i in data) {
          if (data[i].children) {
            _this.updateTableTree(data[i].id, data[i].children);
            dg(data[i].children);
          }
        }
      }
      dg(this.tableData);
    },
    editRow(row, index) {
      //編輯
      this.$set(row, "edit", true);
    },
    delRow(row, index) {
      //刪除行
      let delArr = [];
      function dg(data) {
        for (let i in data) {
          //過濾當(dāng)前新增的數(shù)據(jù)
          if (!data[i].add) {
            delArr.push(data[i].id);
          }
          if (data[i].children) {
            dg(data[i].children);
          }
        }
      }
      dg([row]);
      //刪除
      this.$confirm(
        `刪除選中的 ${row.name} 數(shù)據(jù)項?如果有子項,也會一并刪除!`,
        "提示",
        {
          confirmButtonText: "確定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          if (p.length > 0) {
            //刪除接口
            this.$message({
              message: "刪除成功! ",
              type: "success",
            });
            this.initData();
          } else {
            this.$message({
              message: "刪除成功! ",
              type: "success",
            });
            this.initData();
          }
        })
        .catch(() => {});
    },
    upRow(scope, row, index) {
      console.info(scope, row, index);
      //上移
    },
    downRow(row, index) {
      //下移
    },
    proTableData(data) {
      let _this = this;
      //處理數(shù)據(jù)
      function dg(data) {
        for (let i in data) {
          _this.$set(data[i], "edit", false);
          if (data[i].children) {
            //重要:樹狀節(jié)點數(shù)據(jù)刷新
            _this.updateTableTree(data[i].id, data[i].children);
            dg(data[i].children);
          }
        }
      }
      dg(data);
    },
    initData() {
      //數(shù)據(jù)加載   模仿數(shù)據(jù)請求
      let res = JSON.parse(JSON.stringify(this.sourceData));

      //數(shù)據(jù)處理 添加編輯標識
      this.proTableData(res);
      this.searchSource = JSON.parse(JSON.stringify(res));
      this.tableData = res;
    },
    load(tree, treeNode, resolve) {
      //節(jié)點加載
      setTimeout(() => {
        resolve(tree.children);
      }, 1000);
    },
    handleSelectionChange(val) {
      //全選
      this.cimsDictTable = val;
    },
  },
  mounted() {
    this.initData();
  },
  beforeMount() {
    this.tableMaxHeight = document.body.clientHeight;
  },
};
</script>

<style scoped lang="scss">
.cd-tool {
  display: flex;
  flex-direction: row;
}
.data-table {
  /deep/ .cell {
    display: flex;
    align-items: center;
  }
}
</style>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市靡菇,隨后出現(xiàn)的幾起案子重归,更是在濱河造成了極大的恐慌,老刑警劉巖厦凤,帶你破解...
    沈念sama閱讀 221,548評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件鼻吮,死亡現(xiàn)場離奇詭異,居然都是意外死亡泳唠,警方通過查閱死者的電腦和手機狈网,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,497評論 3 399
  • 文/潘曉璐 我一進店門宙搬,熙熙樓的掌柜王于貴愁眉苦臉地迎上來笨腥,“玉大人,你說我怎么就攤上這事勇垛〔蹦福” “怎么了?”我有些...
    開封第一講書人閱讀 167,990評論 0 360
  • 文/不壞的土叔 我叫張陵闲孤,是天一觀的道長谆级。 經(jīng)常有香客問我烤礁,道長,這世上最難降的妖魔是什么肥照? 我笑而不...
    開封第一講書人閱讀 59,618評論 1 296
  • 正文 為了忘掉前任脚仔,我火速辦了婚禮,結(jié)果婚禮上舆绎,老公的妹妹穿的比我還像新娘鲤脏。我一直安慰自己,他們只是感情好吕朵,可當(dāng)我...
    茶點故事閱讀 68,618評論 6 397
  • 文/花漫 我一把揭開白布猎醇。 她就那樣靜靜地躺著,像睡著了一般努溃。 火紅的嫁衣襯著肌膚如雪硫嘶。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,246評論 1 308
  • 那天梧税,我揣著相機與錄音沦疾,去河邊找鬼。 笑死贡蓖,一個胖子當(dāng)著我的面吹牛曹鸠,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播斥铺,決...
    沈念sama閱讀 40,819評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼彻桃,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了晾蜘?” 一聲冷哼從身側(cè)響起邻眷,我...
    開封第一講書人閱讀 39,725評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎剔交,沒想到半個月后肆饶,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,268評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡岖常,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,356評論 3 340
  • 正文 我和宋清朗相戀三年驯镊,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片竭鞍。...
    茶點故事閱讀 40,488評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡板惑,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出偎快,到底是詐尸還是另有隱情冯乘,我是刑警寧澤,帶...
    沈念sama閱讀 36,181評論 5 350
  • 正文 年R本政府宣布晒夹,位于F島的核電站裆馒,受9級特大地震影響姊氓,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜喷好,卻給世界環(huán)境...
    茶點故事閱讀 41,862評論 3 333
  • 文/蒙蒙 一翔横、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧梗搅,春花似錦棕孙、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,331評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至订雾,卻和暖如春肢预,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背洼哎。 一陣腳步聲響...
    開封第一講書人閱讀 33,445評論 1 272
  • 我被黑心中介騙來泰國打工烫映, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人噩峦。 一個月前我還...
    沈念sama閱讀 48,897評論 3 376
  • 正文 我出身青樓锭沟,卻偏偏與公主長得像,于是被迫代替她去往敵國和親识补。 傳聞我的和親對象是個殘疾皇子族淮,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,500評論 2 359