方法一是自己想出来的,方法二来自忘记哪里看到的了
不知道是不是你要的效果:
方法一:利用input[type="radio"]
css代码:
input {
display: none;
} input[type="radio"]+label {
/* 默认label的样式 */
/* content: "\a0"; */
display: inline-block;
padding: 10px 20px;
background-color: #666;
margin-left: 20px;
color: #fff;
border-radius: 10px;
} input[type="radio"]:checked+label {
/* 当点击label的时候背景颜色发生改变 */
background-color: aqua;
} .row {
display: inline-block;
}
html:
<div v-for="(option, index) in options">
<p>{{option.name}}</p>
<div class="row" v-for="(item, ind) in option.items" @click="select(index, ind)">
<input type="radio" :name="index" :id="item.id" value="">
<!-- 关键在于name这里设为index,让每一行选项的name一样,属性id和label的for属性一致 -->
<label :for="item.id">{{item.msg}}</label>
</div>
</div>
vue实例:
data() {
return {
id: ['', '', ''],
options: [{
items: [{
'msg': '绿色',
"id": "11"
}, {
'msg': "红色",
"id": "12"
}],
name: "颜色"
}, {
items: [{
'msg': "XXX",
"id": "13"
}, {
'msg': "L",
"id": "14"
}, {
'msg': "XXL",
"id": "15"
}],
name: "型号"
}, {
items: [{
'msg': "32G",
"id": "16"
}, {
'msg': "8G",
"id": "17"
}, {
'msg': "4G",
"id": "18"
}],
name: "版本"
}]
}
},
methods: {
select(index, ind) {
var itemId = this.options[index].items[ind].id; //获取选中的id号
this.id.splice(index, 1, itemId); //替换数组id[]中对应的元素,获得所有选中的id
console.log(this.id);
}
}
方法二:利用数组(把每一行当做数组第几个位置eg:a[1]相当于这个数组里的1,每行内选择的元素的索引为数组对应位置的元素值eg:a[1] = xx相当于这里的xx)
css代码:
span {
display: inline-block;
padding: 10px 20px;
background-color: #666;
margin-left: 20px;
color: #fff;
border-radius: 10px;
} .select {
background-color: aqua;
} .row {
display: inline-block;
}
html代码:
<div v-for="(option, index) in options">
<p>{{option.name}}</p>
<span :class="{select:sel[index] == ind}" v-for="(item, ind) in option.items" @click="select(index, ind)">{{item.msg}}</span>
</div>
vue实例:(data中的数据和上面的options一样省略啦)
data() {
return {
sel: [],
id: [],
options: [],
}
},
methods: {
select: function(index, ind) {
this.sel[index] = ind; //让数组sel的第index+1的元素的值等于ind
this.sel = this.sel.concat([]); //因为数组是引用类型,对其中一个变量直接赋值不会影响到另一个变量(并未操作引用的对象),使用concat(操作了应用对象)
this.id[index] = this.options[index].items[ind].id; //获取选中的id
this.id = this.id.concat([]);
console.log(this.id);
}
}
注意:方法二中的vue实例方法中说到引用类型,推荐看:https://www.cnblogs.com/gromimiss/p/6066268.html