uniapp h5项目实现多选按钮/多选标签/多选框

需求:实现简单多选功能,遍历数据,添加样式

1.效果图 

2.以下代码粘贴到代码中,可直接运行,html代码

<view class="page index">
				<view class="list-box">
					<view v-for="(item,index) in typeList" :key="index" @click="choice(index)"
						:class="[item.selected?'selde':'noselde']">
						{{item.selected?item.title:item.title}}
					</view>
				</view>
				<view class="valueList">
					{{selectList}}
				</view>
			</view>

3.js

//给标签赋值
				typeList: [{
						selected: false,
						title: '综合类 20积分一公斤'
					},
					{
						selected: false,
						title: '金属类 20积分一公斤'
					},
					{
						selected: false,
						title: '纸类 20积分一公斤'
					},
					{
						selected: false,
						title: '纸类 20积分一公斤'
					},
					{
						selected: false,
						title: '纸类 20积分一公斤'
					}, {
						selected: false,
						title: '纸类 20积分一公斤'
					},
					{
						selected: false,
						title: '纸类 20积分一公斤'
					}
				],
				selectId: [],

//选择按钮
			choice(index) {
				console.log('index', index)
				//当再次被选中时,取消当前选中项
				if (this.typeList[index].selected == true) {
					this.typeList[index].selected = false;
					//取消选中时删除数组中的值
					for (var i = 0; i < this.selectId.length; i++) {
						if (this.selectId[i] === this.typeList[index].title) {
							this.selectId.splice(i, 1);

						}
					}
					this.selectList = this.selectId
					console.log("选中的值", this.selectId)
				} else {
					this.typeList[index].selected = true;
					this.selectId.push(this.typeList[index].title)
					for (var i = 0; i < this.selectId.length; i++) {
						console.log("选中的值", this.selectId[i])
					}
					this.selectList = this.selectId
					console.log("选中的值", this.selectId)
				}
			}

5.css 

.list-box {
		display: flex;
		justify-content: space-between;
		flex-wrap: wrap;
		// padding: 16rpx;
		border-radius: 10rpx;

		view {
			width: 45%;
			height: 60upx;
			line-height: 60upx;
			text-align: center;
			margin-bottom: 30upx;

			// &:not(:nth-child(3n)) {
			// 	margin-right: calc(10% / 2);
			// }
		}
	}

	/* 已选择 */
	.selde {
		border: 1px solid #3EAAFB;
		background: #3EAAFB;
		color: #FFFFFF;
		border-radius: 20rpx;
		font-size: 20rpx;
		padding: 0 10rpx;
	}

	/* 未选择 */
	.noselde {
		border: 1px solid #959595;
		background: #FFFFFF;
		color: #959595;
		border-radius: 20rpx;
		font-size: 20rpx;
		padding: 0 10rpx;
	}

	.valueList {
		margin-top: 20rpx;
		padding: 20rpx;
		display: flex;
		justify-content: center;
	}

上一篇:C++感受4-HelloWorld中文版——认识编码