项目中不少同仁需要下拉框的n级联动,目前为止查到的资料个人都觉得不太满意,于是自己写了个能够n级联动的下拉框,希望能帮助大家,先上效果图
以下是代码,可以复制直接使用,数据是自己编的,主要提供个思路给大家作为参考
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<h1>选中的详情:{{detailMsg}}</h1>
<div v-for="num in chooseArray.length" :key="num">
<h1>{{num}}级分类</h1>
<el-select v-model="objArr[num-1]" placeholder="请选择" >
<!-- 单纯为el-option绑定单击事件是不生效的,需要为其添加.native 修饰符 -->
<el-option
v-for="item in chooseArray[num-1]"
@click.native="chooseChildrenArr(item)"
:key="item.id"
:value="item.name">
{{item.name}}
</el-option>
</el-select>
</div>
</div>
<!-- 引入vue.js文件 -->
<script src="./vue.js"></script>
<!-- 引入样式element-ui样式 -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<!-- 引入element-ui组件库 -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script>
const app = new Vue({
el:"#app",
data() {
return {
array: [
{
"name": "A",
"level": 1,
"parent_id": null,
"id": 1,
"children": [
{
"name": "A-A",
"level": 2,
"parent_id": 1,
"id": 4,
"children": [
{
"name": "A-A-A",
"level": 3,
"parent_id": 4,
"id": 10,
"children": []
},
{
"name": "A-A-B",
"level": 3,
"parent_id": 4,
"id": 11,
"children": []
},
]
},
{
"name": "A-B",
"level": 2,
"parent_id": 1,
"id": 5,
"children": []
},
]
},
{
"name": "B",
"level": 1,
"parent_id": null,
"id": 3,
"children": [
{
"name": "B-A",
"level": 2,
"parent_id": 3,
"id": 8,
"children": []
},
{
"name": "B-B",
"level": 2,
"parent_id": 3,
"id": 9,
"children": []
}
],
},
{
"name": "C",
"level": 1,
"parent_id": null,
"id": 99,
"children": []
}
],
chooseArray: [],
objArr:[],
detailMsg:''
}
},
methods: {
chooseChildrenArr(val){
if(val.children.length>0){
this.chooseArray[val.level] = val.children
this.chooseArray.splice(val.level+1)
this.objArr.splice(val.level)
}else {
this.chooseArray.splice(val.level);
this.objArr.splice(val.level)
}
this.detailMsg = ''
for(let key in this.objArr){
this.detailMsg +=(key*1+1)+'级分类:' +this.objArr[key] +' '
}
},
},
created() {
var arr= []
this.array.forEach(ele=>{
if(ele.level == 1)arr.push(ele)
})
this.chooseArray[this.chooseArray.length] = arr
},
})
</script>
</body>
</html>
有任何疑问都欢迎指出,看到的都会及时回复
|