说明
一排按钮,点击哪个按钮就改变哪个按钮的样式。如下图
就这个小功能,项目中经常会遇到,每次都脑子what了,一时竟不知道这个逻辑该怎么实现。有时写出来了,过一段时间碰到了又不会了,这次特地记录一下。
上代码:
html模版
<div class="nav">
<div class="twoBtn">
<div class="Dashboard" @click="$router.push('/reportFormRouter')">
仪表盘
</div>
<div class="record">记录</div>
</div>
<!-- 一排按钮(案例)-->
<div class="selectDate">
<div :class="active == 1 ? 'active' : ''" @click="init(1)">
近七日
</div>
<div :class="active == 2 ? 'active' : ''" @click="init(2)">本月</div>
<div :class="active == 3 ? 'active' : ''" @click="init(3)">今年</div>
</div>
</div>
js
export default {
data() {
return {
active: 1,
};
},
methods: {
//改变按钮样式的点击事件
init(data) {
this.active = data;
},
},
}
css样式
.nav {
width: 100%;
margin-bottom: 19px;
display: flex;
justify-content: space-between;
align-items: center;
}
.nav .selectDate {
display: flex;
width: 236px;
margin-right: 30px;
justify-content: space-around;
align-items: center;
}
.nav .selectDate div { //按钮默认样式(没被点击时的样式)
width: 69px;
height: 36px;
border-radius: 4px;
line-height: 36px;
font-weight: 400;
text-align: center;
margin-right: 8px;
font-size: 14px;
color: #666;
border: 1px solid #ddd;
cursor: pointer;
}
.nav .selectDate .active { //按钮被点击后改变的样式
background: #661981;
color: #ffffff;
}