DeeDefaultTree.vue 13.3 KB
Newer Older
wangdanlei's avatar
wangdanlei committed
1
<template>
wangdanlei's avatar
wangdanlei committed
2
  <div :key="updateKey" class="dee-default-tree-com">
wangdanlei's avatar
wangdanlei committed
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
    <el-row v-if="base && base.isShowSerach">
      <el-input v-model="inputVal" clearable placeholder="请输入关键字">
        <el-button slot="append" icon="el-icon-search" />
      </el-input>
    </el-row>
    <div v-if="treeObj && treeObj.headerTools">
      <div v-for="item in treeObj.headerTools" :key="item.key" class="root">
        <span>{{ item.name }}</span>
        <span class="add-root" :title="item.name" @click="buttonClick($event, item)" />
      </div>
    </div>
    <el-tree
      ref="tree"
      style="height: auto;"
      :node-key="base && base.nodeKey ? base.nodeKey : 'id'"
      :data="treeData"
      :props="defaultProps"
      :expand-on-click-node="false"
      :default-expand-all="!base.isPaging"
      :highlight-current="true"
      :lazy="base.isPaging"
      @node-expand="onLoadChildNodes"
      @node-click="nodeClick"
    >
      <span slot-scope="{ data,node }" class="custom-tree-node">
        <span class="changeText" :title="node.label">{{ node.label }}</span>
        <div v-if="treeObj && treeObj.nodeTools">
          <span
            v-for="x in treeObj.nodeTools"
            v-show="showIconFun(x.obscure,node,data)"
            :key="x.key"
            :style="{backgroundImage: 'url('+x.icon+')'}"
            :title="x.name"
            @click.stop="() => buttonClick($event, x, data, node)"
          />
        </div>
      </span>
    </el-tree>
    <!-- 分页加载 -->
    <div v-if="isLoadMore" class="load-more">
      <span @click="loadMoreNode">加载更多</span>
    </div>
    <dee-dialog
      :dialog-visible="dialogVisible"
      :title="dialogTitle"
      width="50%"
      @handleClose="handleClose"
    >
      <DeeStaticCmp v-if="dialogVisible" ref="form" :cmp-options="{value:keyName,typeName:typeName}" :edit-id="editId" :on-form-event-hander="onFormEventHander" />
    </dee-dialog>
  </div>
</template>

<script>
wangdanlei's avatar
wangdanlei committed
57
import { post } from '@/utils/http'
wangdanlei's avatar
wangdanlei committed
58 59 60 61
export default {
  name: 'DeeDefaultTree',
  components: { },
  props: {
wangdanlei's avatar
wangdanlei committed
62 63 64 65
    defaultIsLeaf: {
      type: Boolean,
      default: true
    },
wangdanlei's avatar
wangdanlei committed
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
    base: {
      type: Object,
      default: null
    },
    treeObj: {
      type: Object,
      default: null
    },
    typeName: {
      type: String,
      default: ''
    },
    treeDataProp: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      inputVal: '',
      treeData: [],
      defaultProps: {
        children: this.base && this.base.childrenWord ? this.base.childrenWord : 'children',
wangdanlei's avatar
wangdanlei committed
89 90
        label: (data, node) => this.setLabel(data, node),
        isLeaf: 'isLeaf'
wangdanlei's avatar
wangdanlei committed
91
      },
wangdanlei's avatar
wangdanlei committed
92
      updateKey: 1,
wangdanlei's avatar
wangdanlei committed
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
      dialogVisible: false,
      dialogTitle: '',
      keyName: '',
      editId: '',
      onFormEventHander: {
        'on-submit': () => {
          this.submitFun()
        },
        'on-cancel': () => {
          this.handleClose()
        }
      },
      clickData: null,
      pageFrom: 1,
      // 没有更多
      noMore: false
    }
  },
  computed: {
    /**
     * 分页加载:只对顶层节点进行分页加载,子节点还是全部加载
     * 非分页加载:一次性加载全部节点
     */
    isLoadMore() {
      return this.base && this.base.isPaging && !this.noMore
    }
  },
  watch: {
    base: {
      immediate: true,
      deep: true,
      handler: function(val) {
wangdanlei's avatar
wangdanlei committed
125 126
        this.pageFrom = 1
        this.treeData = []
wangdanlei's avatar
wangdanlei committed
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
        val && val.isAutoLoadData && this.getTreeData()
      }
    },
    treeDataProp: {
      immediate: true,
      deep: true,
      handler: function(val) {
        if (val && ((this.base && !this.base.isAutoLoadData) || !this.base)) {
          this.treeData = this.treeDataProp
        }
      }
    },
    inputVal: {
      handler: function(keyword) {
        const spans = document.getElementsByClassName('changeText')
        if (spans.length > 0) {
          for (let i = 0; i < spans.length; i++) {
            var labelText = spans[i].textContent
            const reg = keyword
              .replace(/\(/g, '\\(')
              .replace(/\)/g, '\\)')
              .replace(/\./g, '\\.')
            const allVal = labelText.match(new RegExp(reg, 'ig'))
            if (allVal) {
              const newAllVal = [...new Set(allVal)]
              for (let j = 0; j < newAllVal.length; j++) {
                if (newAllVal[j]) {
                  const tp = newAllVal[j]
                    .replace(/\(/g, '\\(')
                    .replace(/\)/g, '\\)')
                    .replace(/\./g, '\\.')
                  labelText = labelText.replace(
                    new RegExp(tp, 'g'),
                    '*' + newAllVal[j] + '*'
                  )
                }
              }
              for (let k = 0; k < allVal.length; k++) {
                if (allVal[k]) {
                  labelText = labelText.replace(
                    '*' + allVal[k] + '*',
                    '<span style="color:blue">' +
                  allVal[k] +
                  '</span>'
                  )
                }
              }
            }
            spans[i].innerHTML = labelText
          }
        }
      }
    }
  },
  mounted() {
  },
  methods: {
    setLabel(data, node) {
      if (this.base && this.base.labelWord) {
        let str = ''
wangdanlei's avatar
wangdanlei committed
187 188 189
        if (typeof this.base.labelWord === 'function') {
          str = this.base.labelWord(data, node)
        } else if (this.base.labelWord.indexOf('function') > -1) {
wangdanlei's avatar
wangdanlei committed
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
          try {
            let fn
            // eslint-disable-next-line no-eval
            eval(`fn=${this.base.labelWord}`)
            str = fn(data, node)
          } catch (err) {
            console.log('err', err)
            this.$message.error('请输入正确的表达式')
          }
        } else {
          str = data[this.base.labelWord]
        }
        return str
      } else {
        return data.name
      }
    },
    showIconFun(obscure, node) {
      let result = true
      if (obscure) {
        try {
          let func
          // eslint-disable-next-line no-eval
          eval(`func = function (){return ${obscure}}`)
          result = !func.apply(this)
        } catch (err) {
          console.log('err', err)
          this.$message.error('请输入正确的表达式')
        }
      }
      return result
    },
wangdanlei's avatar
wangdanlei committed
222 223 224 225
    updateTreeNode(nodeData) {
      const node = this.$refs.tree.getNode(nodeData.id)
      node.data = nodeData
    },
wangdanlei's avatar
wangdanlei committed
226 227 228 229 230
    /**
     * 加载数据:
     * 1.加载全部数据
     * 2.分页加载顶层节点,子级节点全部加载
     */
wangdanlei's avatar
wangdanlei committed
231 232 233 234
    getTreeData(parentId, cb) {
      // this.base.defaultParentId 支持自定义根节点parentId值
      const defaultParentId = ['string', 'number'].includes(typeof this.base.defaultParentId) ? this.base.defaultParentId : ''
      parentId = ['string', 'number'].includes(typeof parentId) ? parentId : defaultParentId
wangdanlei's avatar
wangdanlei committed
235 236
      const searchParams = {
        // 排序格式: [{ fieldName: 'modifyTime', sortOrder: 'asc' }]
wangdanlei's avatar
wangdanlei committed
237
        sortItem: [{ fieldName: 'modifyTime', sortOrder: 'desc' }],
wangdanlei's avatar
wangdanlei committed
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
        searchItems: {
          items: []
        }
      }
      // 默认过滤参数
      if (this.base && this.base.searchItemsParams) {
        try {
          const defaultSearchItems = JSON.parse(this.$utils.attachTemplateDoubleToData(this.base.searchItemsParams))
          if (this.$utils.isArray(defaultSearchItems)) {
            searchParams.searchItems.items = defaultSearchItems
          } else {
            searchParams.searchItems = defaultSearchItems
          }
        } catch (error) {
          this.$utils.showMessage('过滤参数JSON配置错误', 'warning')
        }
      }
      // 查询父级下的节点参数
      if (!Array.isArray(searchParams.searchItems.items)) {
        searchParams.searchItems.items = []
      }
      if (this.base.isPaging) {
        if (!cb) {
          searchParams.pageFrom = this.pageFrom
          searchParams.pageSize = this.base.pageSize || 10
        }
        searchParams.searchItems.items.push({ fieldName: this.base.pid || 'parentId', operator: 'EQ', value: parentId })
      }
wangdanlei's avatar
wangdanlei committed
266 267 268 269 270 271 272 273 274 275 276 277 278 279
      // 非分页 OR 分页情况添加子节点
      if (!this.base.isPaging || (this.base.isPaging && cb)) {
        searchParams.pageFrom = 1
        searchParams.pageSize = 9999
      }
      const url = (this.base.url || '').trim() ? this.base.url : ''
      const fetchMethod = url ? post(url, searchParams) : this.$api.searchApi(this.typeName, searchParams)
      fetchMethod.then(res => {
        const firstLoad = !this.treeData.length
        let items = []
        if (this.base.isPaging) {
          items = res.items.content.map(el => {
            if (el.children && el.children.length) {
              el.children = []
wangdanlei's avatar
wangdanlei committed
280
            }
wangdanlei's avatar
wangdanlei committed
281 282 283 284 285 286 287 288 289 290
            return el
          })
        } else {
          items = res.items.content
        }
        if (!Array.isArray(items)) return
        if (this.base.isPaging) {
          if (parentId) {
            // 追加子节点
            cb && cb(items)
wangdanlei's avatar
wangdanlei committed
291
          } else {
wangdanlei's avatar
wangdanlei committed
292 293 294 295 296 297 298
            // 在后面追加节点
            // this.treeData.push.apply(this.treeData, items)
            this.treeData = this.treeData.concat(items)
            this.noMore = !items.length
            if (items.length > 0) {
              this.pageFrom += 1
            }
wangdanlei's avatar
wangdanlei committed
299
          }
wangdanlei's avatar
wangdanlei committed
300 301 302 303 304 305 306 307 308 309
        } else {
          this.treeData = this.$utils.generateTree(items, { id: this.base.selfId, pid: this.base.pid })
        }
        if (firstLoad && this.treeData.length) {
          this.$nextTick(function() {
            this.$refs.tree.setCurrentKey(this.base && this.base.nodeKey ? this.treeData[0][this.base.nodeKey] : this.treeData[0].id)
          })
          this.nodeClick(this.treeData[0])
        }
      })
wangdanlei's avatar
wangdanlei committed
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
    },
    buttonClick(e, item, data, node) {
      this.clickData = data
      if (item.btnValue && this[item.btnValue]) {
        this[item.btnValue](item, data, node)
      } else {
        this.$emit('handerTreeFun', item, data, node)
      }
    },
    add(item) {
      this.keyName = item.keyName
      this.dialogTitle = '新增'
      this.editId = ''
      this.dialogVisible = true
    },
    edit(item, data) {
      this.keyName = item.keyName
      this.dialogTitle = '编辑'
      this.editId = data.id
      this.dialogVisible = true
    },
    remove(item, data) {
      this.$utils.showConfirm(
        `你是否确定删除选中的数据`,
        '提示',
        'warning',
        '确定',
        '取消',
        () => {
          this.$api.batchDelete(this.typeName, data.id).then(res => {
            if (this.base && !this.base.isAutoLoadData) {
              this.$emit('handerTreeFun', { btnValue: 'refreshTreeLoad' })
            } else {
              this.getTreeData()
            }
            this.$utils.showMessageSuccess('删除成功!')
          })
        }
      )
    },
    submitFun() {
      const form = { ...this.$refs.form.propForm }
      if (form.id) {
        form.operator = 'MODIFY'
      } else {
        form.parentId = this.clickData ? this.clickData.id : 0
      }
      this.$getService(this.typeName).save(form).then(res => {
wangdanlei's avatar
wangdanlei committed
358 359 360 361 362
        this.$utils.showMessageSuccess(form.id ? '编辑成功' : '新增成功')
        this.dialogVisible = false
        this.pageFrom = 1
        this.updateKey += 1
        this.treeData = []
wangdanlei's avatar
wangdanlei committed
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
        if (this.base && !this.base.isAutoLoadData) {
          this.$emit('handerTreeFun', { btnValue: 'refreshTreeLoad' }, res.items)
        } else {
          this.getTreeData()
        }
      })
    },
    nodeClick(data) {
      this.$emit('nodeClick', data, this.treeData)
    },
    handleClose() {
      this.dialogVisible = false
    },
    loadMoreNode() {
      this.getTreeData()
    },
    onLoadChildNodes(data, node, nodeCmp) {
      if (node.childNodes.length > 0) return
      node.loading = true
      const parentId = data[this.base.selfId || 'id']
      this.getTreeData(parentId, (items) => {
        node.loading = false
        node.loaded = true
        if (items.length) {
          items.forEach(m => {
            this.$refs.tree.append(m, node)
          })
        } else {
          node.isLeaf = true
        }
      })
    }
  }
}
</script>

<style lang="scss" >
.dee-default-tree-com {
  height: 100%;
wangdanlei's avatar
wangdanlei committed
402
  font-size: 14px;
wangdanlei's avatar
wangdanlei committed
403 404 405 406 407 408 409 410 411 412 413 414 415
  .el-row {
    margin-bottom: 15px;
  }
  .root {
    display: flex;
    justify-content: space-between;
    padding-left: 8px;
  }
  .root:hover .add-root {
    visibility: visible;
  }
  .add-root {
    display: inline-block;
wangdanlei's avatar
wangdanlei committed
416 417
    width:14px;
    height:14px;
wangdanlei's avatar
wangdanlei committed
418 419 420 421 422 423 424 425
    margin: auto 4px;
    background-size: cover;
    background-position: center;
    background-image: url('/icons/c-add.png');
    visibility: hidden;
  }
  .el-tree {
    height: calc(100% - 50px);
wangdanlei's avatar
wangdanlei committed
426
    overflow-y: auto;
wangdanlei's avatar
wangdanlei committed
427 428 429 430 431 432 433 434 435 436 437 438
  }
  .custom-tree-node {
    width: 100%;
    display: flex;
    justify-content: space-between;
    div {
      width: 100px;
      display: flex;
      justify-content: flex-end;
    }
    div > span {
      display: none;
wangdanlei's avatar
wangdanlei committed
439 440 441
      width:14px;
      height:14px;
      margin: 0 6px;
wangdanlei's avatar
wangdanlei committed
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
      background-size: cover;
      background-position: center;
    }
  }
  .custom-tree-node:hover div span{
    display: inline-block;
  }
  .load-more {
    line-height: 50px;
    height: 50px;
    text-align: center;
    span {
      margin: auto;
      color: #2f90e2;
      height: 26px;
      line-height: 26px;
      padding: 0 20px;
      font-size: 12px;
      background: #e7f2ff;
      border-radius: 13px;
      display: inline-block;
      cursor: pointer;
    }
  }
}
</style>