级联选择器回显问题
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
@import url('//unpkg.com/element-ui@2.13.2/lib/theme-chalk/index.css');
</style>
<script src="//unpkg.com/vue/dist/vue.js"></script>
<script src="//unpkg.com/element-ui@2.13.2/lib/index.js"></script>
</head>
<body>
<div id="app">
<div class="block">
<span class="demonstration">默认 click 触发子菜单</span>
<el-cascader
v-model="value"
:options="options"
:props="{ expandTrigger: 'click', checkStrictly: true }"
@change="handleChange"
></el-cascader>
</div>
</div>
<script>
var Main = {
data() {
return {
value: [], // 选中的绑定值
options: [ // 数据源
{
value: 'zhinan',
label: '指南',
children: [
{
value: 'shejiyuanze',
label: '设计原则',
children: [
{
value: 'yizhi',
label: '一致',
},
{
value: 'fankui',
label: '反馈',
}
],
},
{
value: 'daohang',
label: '导航',
children: [
{
value: 'cexiangdaohang',
label: '侧向导航',
},
{
value: 'dingbudaohang',
label: '顶部导航',
},
],
},
],
},
{
value: 'zujian',
label: '组件',
children: [
{
value: 'basic',
label: 'Basic',
children: [
{
value: 'layout',
label: 'Layout 布局',
},
{
value: 'button',
label: 'Button 按钮',
},
],
},
{
value: 'form',
label: 'Form',
children: [
{
value: 'radio',
label: 'Radio 单选框',
},
{
value: 'checkbox',
label: 'Checkbox 多选框',
},
{
value: 'switch',
label: 'Switch 开关',
},
{
value: 'slider',
label: 'Slider 滑块',
},
{
value: 'form',
label: 'Form 表单',
},
],
},
{
value: 'data',
label: 'Data',
children: [
{
value: 'table',
label: 'Table 表格',
},
{
value: 'tag',
label: 'Tag 标签',
}
],
}
],
},
],
}
},
created() {
const selected = 'radio'
// 根据后端返回的选定值,查询出符合级联选择器的数组
const result = this.getSelectedArr(selected, this.options)
console.log(result)
},
methods: {
handleChange(value) {
console.log(value)
},
/**
* key 待查询结果
* options 数据源
* keyName 查询数据源的那个属性,和待查询结果key比对
* childrenName 数据源的子节点名称
*/
getSelectedArr(key, options, keyName = 'value', childrenName = 'children'){
const tempArr = [] // 在递归时操作的数组
let depth = 0 // 定义全局层级
let resultArr = [] // 存放结果的数组
// 递归调用
const childrenEach = (options, curDepth) => {
// 查询给定值在树结构的位置
for (let i = 0; i < options.length; i++) {
depth = curDepth
const curKey = options[i][keyName]
tempArr[depth] = curKey
if (curKey === key) {
// 查找成功
resultArr = [...tempArr]
break
} else {
if (options[i][childrenName]) {
depth++
// 有子节点,继续查询
childrenEach(options[i][childrenName], depth)
} else {
// 查询失败,并且没有子节点了
return []
}
}
}
return resultArr
}
return childrenEach(options, depth)
},
},
}
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')
</script>
</body>
</html>
级联选择器回显问题