今天找到一个不错的element ui树形选项
<template> <div class="about"> <!-- 选择器选项以树形控件展示 --> <el-select v-model="form.id" placeholder="请选择" ref="selectTree"> <el-option :key="form.id" :value="form.id" :label="form.label" hidden/> <el-tree :data="data" :props="defaultProps" node-key="id" accordion highlight-current @node-click="handleNodeClick"/> </el-select> </div> </template> <script> export default { data () { return { data: [{ label: '一级 1', children: [{ label: '二级 1-1', children: [{ label: '三级 1-1-1' }] }] }, { label: '一级 2', children: [{ label: '二级 2-1', children: [{ label: '三级 2-1-1' }] }, { label: '二级 2-2', children: [{ label: '三级 2-2-1' }] }] }, { label: '一级 3', children: [{ label: '二级 3-1', children: [{ label: '三级 3-1-1' }] }, { label: '二级 3-2', children: [{ label: '三级 3-2-1' }] }] }], defaultProps: { children: 'children', label: 'label' }, form: { id: '', value: '' } } }, methods: { handleNodeClick (data) { // console.log(data) this.form = { id: data.label, value: data.label } // 使 input 失去焦点,并隐藏下拉框 this.$refs.selectTree.blur() } } } </script>
很好用,效果:
组件模式
<template> <div class="about"> <!-- 树形选择器 --> <el-select v-model="selectedValue" placeholder="请选择" ref="selectTree" @visible-change="handleVisibleChange"> <el-option :value="selectedValue" hidden/> <el-tree :data="treeData" :props="defaultProps" node-key="id" empty-text="没有可选数据" accordion :indent="20" :default-expand-all="defaultExpandAll" :highlight-current="true" @node-click="handleNodeClick" /> </el-select> </div> </template> <script> export default { name: 'SelectedTree', props: { // 树形结构数据 treeData: { type: Array, required: true }, // 默认属性配置 defaultProps: { type: Object, default() { return { children: 'children', label: 'label' } } }, // 是否默认展开所有节点 defaultExpandAll: { type: Boolean, default: false }, // 初始选中值 value: { type: String, default: '' } }, data() { return { selectedValue: this.value // 使用 prop 设置初始值 } }, watch: { value(newValue) { this.selectedValue = newValue } }, methods: { handleNodeClick(data) { this.selectedValue = data.label this.$emit('input', data.id) this.$emit('node-click', data) this.$refs.selectTree.blur() // 隐藏下拉框 }, handleVisibleChange(visible) { if (!visible) { // 当下拉框隐藏时触发 this.$emit('close') } } } } </script> #调用 <SelectedTree :tree-data="category_list" :default-props="{ children: 'children', label: 'label' }" :value="form.category_name" :default-expand-all="true" @node-click="chooseTree" />