一、主要效果:
a.下拉选中值后,自动收起
b.没值回显,选中select时,下拉展开滚动条默认在初始位置
二、代码
a.数据格式参考官方文档
//template
<el-form-item :label="$t('salesDesc') + ':'" prop="salesCode">
<el-select size="small" style="width: 100%" ref="selectTree" clearable v-model="ruleForm.salesOfficeDesc" :placeholder="$t('select')" @clear="clearOfficeDesc">
//el-options是关键
<el-option hidden :key="editCheckCode" :value="editCheckCode" :label="ruleForm.salesOfficeDesc"></el-option>
<el-tree ref="tree" class="tree" :data="officeTreeData" :props="defaultProps" show-checkbox node-key="r3code" default-expand-all @check-change="checkChange" @node-click="handleNodeClick"></el-tree>
</el-select>
</el-form-item>
//数据
data(){
return: {
ruleForm: {
salesOfficeCode: '', // 当前选择子公司的orgId
salesOfficeDesc: '' // 当前选择子公司的lebal
},
defaultProps: {
children: 'children',
label: 'label'
},//设置关联字段
editCheckCode: '',//选择的id
officeTreeData: [], // 业务部门tree数据
}
}
methods: {
// 查看详情
serchMessage() {
API.getSelectOneData(this.Hid)
.then(res => {
/*有值,回显*/
if (res.data.salesOfficeCode) {
this.$nextTick(() => {
console.log(res.data.salesOfficeCode, 'res.data.r3code');
this.editCheckCode = res.data.salesOfficeCode;
this.$refs.tree.setCheckedKeys([res.data.salesOfficeCode]);
});
} else {
/*没值,回显空数组*/
this.$refs.tree.setCheckedKeys([]);
}
})
},
// 选中tree-checked
checkChange(item, node) {
if (node === true) {
this.editCheckCode = item.r3code;
this.ruleForm.salesOfficeDesc = item.label; // 选中当前名称
this.ruleForm.salesOfficeCode = item.r3code; // 选中当前code
this.$refs.tree.setCheckedKeys([item.r3code]);
this.$refs.selectTree.blur();//收起下拉框
} else {
if (this.editCheckCode === item.r3code) {
this.$refs.tree.setCheckedKeys([item.r3code]);
}
}
},
// 清楚业务部门
clearOfficeDesc() {
this.editCheckCode = '';
this.ruleForm.salesOfficeDesc = ''; // 选中当前名称
this.ruleForm.salesOfficeCode = ''; // 选中当前code
this.$refs.tree.setCheckedKeys([]); // 清楚tree选中的状态
},
// tree点击当前行的时候
handleNodeClick(item) {
// 自己定义的editCheckId,防止单选出现混乱
this.editCheckCode = item.r3code;
this.ruleForm.salesOfficeDesc = item.label; // 选中当前名称
this.ruleForm.salesOfficeCode = item.r3code; // 选中当前code
this.$refs.tree.setCheckedKeys([item.r3code]);
this.$refs.selectTree.blur(); //收起下拉框
},
// 获取业务部门
getOfficeCodeTree() {
API.getOrganizationUserList()
.then(res => {
if (res.status && res.data && Object.keys(res.data).length > 0) {
/*递归*/
const topLvList = [];
topLvList.push(res.data);
const dp = (list, lv) => {
list.length && lv++;
return list.map(v => {
const nChild = v.organizationReturnDTOList && v.organizationReturnDTOList.length > 0 ? dp(v.organizationReturnDTOList, lv) : v.organizationReturnDTOList;
return {
...v,
level: lv,
label: v.orgName,
children: nChild,
//disabled: lv === 4 ? false : true,//控制层级是否可以选中
//r3code: lv === 4 ? v.r3code : v.orgCode //
};
});
};
const ret = dp(topLvList, 0);
this.officeTreeData = ret;
this.options = ret;
}
})
.catch(err => {
this.$message.error(err.msg || '请求失败');
});
}
}
总结: 添加value属性是关键