问题描述
因为分类数据太多,首次加载时间太长,和业务沟通改成异步加载子节点,解决了加载缓慢的问题,但编辑的时候回显就不能显示了,因为赋值的时候,下拉框数据中还没有加载已选中的项。该怎么办呢…
解决方案
结合业务考虑,因为分类的ID是输入框手动输入的,没有特定的格式,只根据多个分类的ID用分号分隔了,无法找到其父节点的分类ID,所以不能用递归调用数据的方法。想了一个让分类显示的方法,将需要回显的数据插入到categoryData
中,实现编辑分类的回显。
示例代码
<template><TreeSelectv-if="item.key === 'broader'"v-model="form[item.key]":data="categoryData":load-data="loadTreeList"multiple/>
</template>
<script>export default {props: {categoryData: {type: Array,default: () => []}},data () {return {value: [],nextValue: 1,data: [{title: 'parent1',value: 'parent1',loading: false,selected: false,checked: false,children: []}]}},methods: {findById (node, targetId) {// 如果当前节点的value等于targetId,直接返回当前节点if (node.value === targetId) {return node}// 如果当前节点有子节点,则遍历子节点if (node.children && node.children.length) {for (let child of node.children) {const foundNode = this.findById(child, targetId)if (foundNode) {// 如果找到了匹配的节点则返回return foundNode}}}// 如果遍历完所有的子节点都没有找到匹配的节点,则返回nullreturn null},initTreeData (categoryIds, labels) {const data = _.cloneDeep(this.categoryData)const existData = []const categoryNodes = []for (let i = 0, len = categoryIds.length; i < len; i++) {data.forEach(item => {const target = this.findById(item, categoryIds[i]) if (target) {existData.push(target)}})categoryNodes.push({title: labels[i],value: categoryIds[i],selected: false})}categoryNodes.forEach(node => {const target = existData.find(existNode => existNode.value === node.value)if (!target) {this.categoryData.push(node)}})},async loadTreeList (broader, callback) {return new Promise((resolve, reject) => {const params = {broader: broader.categoryId,entryName: this.entryName}getTreeList(params).then(res => {const data = res.map(item => {item.title = item.prefLabelitem.value = item.categoryIditem.selected = falseitem.checked = falseitem.loading = falsereturn item})callback(data)resolve(data)}).catch(err => {reject(err)})}) },init (row) {this.visible = truethis.entryId = row.entryIdthis.entryName = row.entryNamethis.title = '新增'if (row && row.id) {this.id = row.idthis.title = '编辑'this.form = { ...row }if (this.form.broader) {this.form.broader = row.broader.split(';')this.initTreeData(row.broader.split(';'), row.category_pref_label.split(';'))}if (row.alt_label) {this.altLabelList = row.alt_label.split(';')}}},}}
</script>
参考文档:
https://www.iviewui.com/view-ui-plus/component/form/tree-select#load