基于vue+element+select实现的自定义控件selectTree
基于vue+element+select实现的自定义控件selectTree,效果如图:
单选:
输出值:"tree":3
多选:
输出值:"tree":[2,3]
代码如下:
<template> <el-select ref="selectTree" v-model="value" :placeholder="placeholder" v-bind="$attrs" clearable @remove-tag="removeTag" > <el-option value="" /> <el-tree ref="treeOption" :show-checkbox="this.$attrs.multiple" default-expand-all highlight-current accordion node-key="id" check-on-click-node :data="options" :props="defaultProps" @check="checkNode" /> </el-select> </template> <script> export default { name: 'CisTreeSelect', props: { placeholder: { type: String, default: () => { return '请选择' } }, // 节点数据 options: { type: Array, // 必须是树形结构的对象数组 default: () => { return [] } }, // 设置lable value属性 defaultProps: { type: Object, default: () => { return { value: 'id', // ID字段名 label: 'label', // 显示名称 children: 'childList' // 子级字段名 } } }, // 默认勾选的节点 defaultCheckNodes: { type: Array, // 已经分配的资源 default: () => { return [] } } }, data() { return { value: [] } }, methods: { // 删除tag时, removeTag(val) { // 取消勾选 const treeOption = this.$refs.treeOption treeOption.setChecked(val, false, false) // 重新给控件赋值 this.$emit('input', this.value) }, // 勾选节点, checkNode(node, treeStatus) { node.value = node.id node.currentLabel = node.label // 给selectTree的cachedOptions赋值 设置node.label,使用页面显示label值 const selectTree = this.$refs.selectTree selectTree.cachedOptions.push(node) selectTree.handleOptionSelect(node, true) this.$emit('input', this.value) } } } </script> <style scoped> /* 去除tree上面的一行高度 */ .el-scrollbar .el-scrollbar__view .el-select-dropdown__item { height: auto; padding: 0; } </style>
使用方法:
<template> <div> <div> <el-form> <el-form-item label="下拉树" label-width="100px" class="item"> <select-tree v-model="selectData.tree" :options="options" :multiple="true" /> </el-form-item> <el-form-item> <el-button type="primary" @click="onSubmit">检索</el-button> <el-button>重置</el-button> </el-form-item> </el-form> </div> </div> </template> <script> import SelectTree from '../SelectTree' export default { name: 'DragSelect', components: { SelectTree }, props: { value: { type: Array, required: true } }, data() { return { selectData: { tree: null }, options: [{ id: 1, label: '北京市', childList: [{ id: 2, label: '朝阳区' }, { id: 3, label: '东城区' }] }, { id: 4, label: '黑龙江', childList: [{ id: 5, label: '哈尔滨' }, { id: 6, label: '佳木斯' }] }, { id: 7, label: '辽宁省', childList: [{ id: 8, label: '沈阳市' }, { id: 9, label: '大连市' }] } ] } }, mounted() { }, methods: { handleRemoveTag(val) { console.dir(val) }, onSubmit() { console.dir(JSON.stringify(this.selectData)) } } } </script>