css:
.recharge_box{display: flex;padding: 0.1rem 0.1rem;justify-content: space-between;} .recharge{width: 2rem;height: 1rem;text-align: center;line-height: 1rem; border: 1px solid #eee;border-radius: 0.2rem;font-size: 0.3rem;} .selected{background: rgb(50, 115, 220);}
html:
<div id="demo">
<div class="recharge_box">
<div class="recharge" v-for="(item,index) in data_list" @click="clickMe(index)" :class="index==idx?'selected':''">
充 <span>{{item.price}}</span> 元 </div> </div>
</div>
js:
<script>
new Vue({
el:"#demo",
data(){
return{
data_list:[
{
id:1,
price:10
},
{
id:2,
price:50
},
{
id:3,
price:100
},
],
idx:0,
}
},
methods:{
clickMe(index){
console.log(index)
this.idx=index
}
},
created(){
},
mounted(){
}
})
</script>
思路:
因為循環列表的第一個元素的索引為0,所以先定義一個idx變量為0,然后用三元運算符動態綁定class,初始化渲染的時候idx和index都為0,所以第一個循環的列表會被默認選中。
當你點擊之后,index會將索引賦值給idx,index和idx依然相等,這樣就能實現動態改變classl了
效果圖:

點擊后

