index.vue 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <template>
  2. <el-table-column :prop="prop" v-bind="$attrs">
  3. <template slot-scope="scope">
  4. <span @click.prevent="toggleHandle(scope.$index, scope.row)" :style="childStyles(scope.row)">
  5. <i :class="iconClasses(scope.row)" :style="iconStyles(scope.row)"></i>
  6. </span>
  7. <span style="padding-left: 10px;">
  8. <slot :data="scope.row" v-bind="scope">
  9. {{ scope.row[prop] }}
  10. </slot>
  11. </span>
  12. </template>
  13. </el-table-column>
  14. </template>
  15. <script>
  16. import isArray from 'lodash/isArray'
  17. export default {
  18. name: 'table-tree-column',
  19. props: {
  20. prop: {
  21. type: String
  22. },
  23. treeKey: {
  24. type: String,
  25. default: 'id'
  26. },
  27. parentKey: {
  28. type: String,
  29. default: 'parentId'
  30. },
  31. levelKey: {
  32. type: String,
  33. default: '_level'
  34. },
  35. childKey: {
  36. type: String,
  37. default: 'childrens'
  38. }
  39. },
  40. methods: {
  41. childStyles (row) {
  42. let size = row.parentIds.split(',').length - 1
  43. return {'padding-left': (size > 0 ? size * 10 : 0) + 'px'}
  44. },
  45. iconClasses (row) {
  46. return [!row._expanded ? 'el-icon-caret-right' : 'el-icon-caret-bottom']
  47. },
  48. iconStyles (row) {
  49. return {'visibility': this.hasChild(row) ? 'visible' : 'hidden'}
  50. },
  51. hasChild (row) {
  52. return (isArray(row[this.childKey]) && row[this.childKey].length >= 1) || false
  53. },
  54. // 切换处理
  55. toggleHandle (index, row) {
  56. if (this.hasChild(row)) {
  57. let data = this.$parent.store.states.data.slice(0)
  58. data[index]._expanded = !data[index]._expanded
  59. if (data[index]._expanded) {
  60. data = data.splice(0, index + 1).concat(row[this.childKey]).concat(data)
  61. } else {
  62. data = this.removeChildNode(data, row[this.treeKey])
  63. }
  64. this.$parent.store.commit('setData', data)
  65. this.$nextTick(() => {
  66. this.$parent.doLayout()
  67. })
  68. }
  69. },
  70. // 移除子节点
  71. removeChildNode (data, parentId) {
  72. let parentIds = isArray(parentId) ? parentId : [parentId]
  73. if (parentId.length <= 0) {
  74. return data
  75. }
  76. let ids = []
  77. for (let i = 0; i < data.length; i++) {
  78. if (parentIds.indexOf(data[i][this.parentKey]) !== -1 && parentIds.indexOf(data[i][this.treeKey]) === -1) {
  79. ids.push(data.splice(i, 1)[0][this.treeKey])
  80. i--
  81. }
  82. }
  83. return this.removeChildNode(data, ids)
  84. }
  85. }
  86. }
  87. </script>