index.vue 2.4 KB

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