el-cascader动态加载二级
时间: 2023-11-07 21:15:27 浏览: 65
你可以使用 `el-cascader` 组件来实现动态加载二级数据。首先,你需要设置 `:options` 属性为一个数组,该数组包含你的一级选项的数据。然后,你可以通过监听 `change` 事件来获取当前选中的一级选项的值,从而加载对应的二级数据。
以下是一个示例代码:
```html
<template>
<div>
<el-cascader
:options="options"
@change="loadSecondLevel"
v-model="selectedOptions"
placeholder="请选择"
></el-cascader>
</div>
</template>
<script>
export default {
data() {
return {
options: [
{
value: '1',
label: '一级选项1'
},
{
value: '2',
label: '一级选项2'
},
// 更多一级选项...
],
selectedOptions: [] // 用于存储当前选中的选项值
}
},
methods: {
loadSecondLevel(value) {
// 根据一级选项的值加载对应的二级数据
// 这里可以发送异步请求获取数据,或者根据一级选项的值从预定义数据中获取
// 然后将二级数据设置到一个变量中,例如 secondLevelOptions
// 最后将该变量赋值给 el-cascader 的 :options 属性
// 示例:假设一级选项值为 '1',且对应的二级数据为 [{ value: '11', label: '二级选项1-1' }, { value: '12', label: '二级选项1-2' }]
const secondLevelOptions = [
{
value: '11',
label: '二级选项1-1'
},
{
value: '12',
label: '二级选项1-2'
}
];
// 设置二级数据到 el-cascader 的 :options 属性
this.$set(this.options.find(option => option.value === value), 'children', secondLevelOptions);
}
}
}
</script>
```
上述示例中,当选择一级选项时,会触发 `change` 事件,然后调用 `loadSecondLevel` 方法来加载对应的二级数据,并将其设置到 `el-cascader` 组件的 `:options` 属性中。
请根据你的实际需求修改示例代码中的数据和加载逻辑。希望能帮到你!如有其他问题,请继续提问。