vue选项卡 ,v-for循环数据列表,初始循环中的第一个为选中状态class,点击改变class


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了

效果图:

点击后


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM