Element树型下拉框/vue2树型下拉框/TreeSelect/树型下拉
以下是一个简单的Vue 2树型下拉框组件的示例代码:
<template>
<div>
<select v-model="selectedId" @change="handleChange">
<optgroup v-for="node in treeData" :label="node.label">
<option v-for="child in node.children" :value="child.id">{{ child.name }}</option>
</optgroup>
</select>
</div>
</template>
<script>
export default {
props: {
treeData: {
type: Array,
required: true
}
},
data() {
return {
selectedId: null
};
},
methods: {
handleChange() {
this.$emit('change', this.selectedId);
}
}
};
</script>
使用方法:
<template>
<div>
<tree-select :tree-data="categoryTree" @change="handleCategoryChange"></tree-select>
</div>
</template>
<script>
import TreeSelect from './TreeSelect.vue';
export default {
components: {
TreeSelect
},
data() {
return {
categoryTree: [
{
id: 1,
label: 'Category 1',
children: [
{ id: 11, name: 'Subcategory 1.1' },
{ id: 12, name: 'Subcategory 1.2' }
]
},
{
id: 2,
label: 'Category 2',
children: [
{ id: 21, name: 'Subcategory 2.1' },
{ id: 22, name: 'Subcategory 2.2' }
]
}
]
};
},
methods: {
handleCategoryChange(selectedId) {
console.log('Selected category ID:', selectedId);
}
}
};
</script>
在这个例子中,TreeSelect
组件接收一个treeData
属性,它是一个树形结构的对象数组,每个对象代表一个节点,包含id
、label
和children
属性。组件使用select
元素渲染树型下拉框,并在用户选择时触发change
事件,其中包含被选节点的id
。父组件通过监听change
事件来处理节点选择的结果。
评论已关闭