基於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>