场景一:用户点击按钮后动态切换按钮选中样式(如图)
<view class="state-btn-content">
<view @tap="selectState" data-state="over" :class="[whichSelected=='over'?'state-btn-selected':'state-btn-noselect']">已上线</view>
<view @tap="selectState" data-state="pre" :class="[whichSelected=='pre'?'state-btn-selected':'state-btn-noselect']">未开始</view>
</view>
//选择状态
selectState(e){
this.whichSelected=e.currentTarget.dataset.state
}
.state-btn-content{
//write your style
.state-btn-selected{ ... }
.state-btn-noselect{ ... }
}
注:需要注意的就是一个标签里尽量不要同时用静态class与动态class,可能会造成兼容问题。最好只是用一种方式的,如上代码里为了实现动态改变样式只使用了:class
错误示范:<view @click="selectState" data-state="over" class="state-btn-noselect" :class="[whichSelected=='over'?'state-btn-selected':'']">已上线</view>
场景二:给标签渲染多种颜色(如图)
<view :class="['every-sign-item',`signstyle-${index%6}`]" v-for="(item,index) in preSignList" :key="index">{{item.name}}</view>
.every-sign-item{
padding: 4rpx 16rpx;
border-radius: 24rpx;
font-size: 24rpx;
margin-right: 20rpx;
margin-bottom: 20rpx;
}
.signstyle-0{
color: #3ac9e3;
border: 1px solid #3ac9e3;
}
.signstyle-1{
color: #fd8888;
border: 1px solid #fd8888;
}
.signstyle-2{ ... }
.signstyle-3{ ... }
.signstyle-4{ ... }
.signstyle-5{ ... }