先来张GIF图
html
<article id="app">
<select id="sel" @change="checkedParent()">
<option v-for="opt in option" :value="opt.id" :name="opt.name">{{opt.name}}</option>
</select>
<span v-for="cate in category">
<input @click="checkedSonItem(cate)" type="checkbox" :name="cate.name" :value="cate.id" v-model="cate.sta"/>{{cate.name}}
</span>
</article>
js
let app = new Vue({
el: '#app',
data: {
option: [
{id: 0, name: '其他',selected:true},
{id: 1, name: '大力水手'},
{id: 2, name: '天眼神虎/天眼'},
{id: 3, name: '小园'},
{id: 4, name: '熊二'}
],
category: [
{id: 0, name: '牛皮糖', sta: false},
{id: 1, name: '蜂蜜', sta: false},
{id: 2, name: '菠菜', sta: false},
{id: 3, name: '甜筒', sta: false}
],
//定义一个二维数组
arr2: [
[
//其他
],
[
//大力水手
2
],
[
//天眼神虎/天眼
0,3
],
[
//小园
0,1,2,3
],
[
//熊二
1
]
]
},
methods: {
checkedParent: function() {
let that=this;
//选择的出行场景id
let num=Number(sel.options[sel.selectedIndex].value);
//arr就是 当前出行场景 对应的 条件id数组
let arr = that.arr2[num];
//将所有条件选择框重置为false
that.category.forEach(function(info) {info.sta = false});
for( var i=0;i<arr.length;i++){
that.category.forEach(function(info) {
if(info.id == arr[i]){
info.sta = true;
}
});
}
},
checkedSonItem: function(info) {
if(info.sta){
info.sta = false;
}else{
info.sta = true;
}
let len = 0;
this.category.forEach(function(item) {
if(item.sta==true){
len++;
}
});
let arr = new Array(len);
let n = 0;
this.category.forEach(function(item) {
if (item.sta==true) {
arr[n] = item.id;
n++;
}
});
//arr 就是所有的选中的出行条件的id数组
//遍历arr2
for(var i=0;i<this.arr2.length;i++){
//bean是一个出行场景
let bean = this.arr2[i];
//判断当前出行场景id数组arr 是否与 选中的出行条件的id数组bean 完全相同(顺序可以不同)
if( this.isContained(arr,bean) ){
for(var f=0;f<sel.length;f++){
sel[f].selected = false;
}
sel[i].selected = true;
return;
}
}
// 遍历option,让所有选项都隐藏
for(var f=0;f<sel.length;f++){
sel[f].selected = false;
}
//将“其他”选项显示
sel[0].selected = true;
},
// 比较两个数组
isContained(aa, bb) {
for(var i = 0;i<bb.length;i++){
var num = 0;
for(var j=0;j<aa.length;j++){
if(bb[i] == aa[j]){
num++;
}
}
if(num < 1){
return false;
}
}
for(var i = 0;i<aa.length;i++){
var num = 0;
for(var j=0;j<bb.length;j++){
if(bb[j] == aa[i]){
num++;
}
}
if(num < 1){
return false;
}
}
return true;
}
}
})
css
select{
width: 200px;
height: 30px;
line-height: 30px;
box-shadow: 0 0 5px #ccc;
border: 1px solid #ccc;
border-radius: 4px;
position: relative;
color: #393e46;
display: inline-block;
border: none;
outline: none; /* 清除select聚焦时候的边框颜色 */
appearance: none;/* 隐藏select的下拉图标 */
-webkit-appearance: none;
-moz-appearance: none;
text-align: center;
}