在uniapp中,可以使用v-for指令进行列表渲染,并通过绑定点击事件来实现点击盒子切换的效果我们这里以选择月份进行举例
1、首选在数据中定义一个包含对象的数组,每个对象包含月份和对应id 例如:
<script>
export default{
data(){
return{
activeIndex:0,//索引
box:[
{
time:'2022',
boxs:[
{
id:'1',
text:'一月'
},
{
id:'2',
text:'二月'
},
{
id:'3',
text:'三月'
},
{
id:'4',
text:'四月'
},
{
id:'5',
text:'五月'
},
{
id:'6',
text:'六月'
},
{
id:'7',
text:'七月'
},
{
id:'8',
text:'八月'
},
{
id:'9',
text:'九月'
},
{
id:'10',
text:'十月'
},
{
id:'11',
text:'十一月'
},
{
id:'12',
text:'十二月'
}
]
},
{
time:'2023',
boxs:[
{
id:'13',
text:'一月'
},
{
id:'14',
text:'二月'
},
{
id:'15',
text:'三月'
},
{
id:'16',
text:'四月'
},
{
id:'17',
text:'五月'
},
{
id:'18',
text:'六月'
},
{
id:'19',
text:'七月'
},
{
id:'20',
text:'八月'
},
{
id:'21',
text:'九月'
},
{
id:'22',
text:'十月'
},
{
id:'23',
text:'十一月'
},
{
id:'24',
text:'十二月'
}
]
}
]
}
},
methods:{
samsung(id){
this.activeIndex = id
}
}
}
</script>
methods中的方法是通过找到对应的id的值赋值给索引activeIndex从而进行tap切换
2、接下来,在模版中使用v-for指令遍历box数组渲染每个年份,在从box数组中在v-for渲染每个年份中的月份,并为每个月份绑定tap事件:
<template>
<view>
<view class="big" v-for="(item,index) in box" :key="index">
<view style="width: 100%; height: 100rpx; line-height: 100rpx; text-align:center">{{item.time}}</view>
<view class="little" v-for="(items,indexs) in item.boxs" :key="items.id" :class="{activeclass: activeIndex === items.id}" @tap="samsung(items.id)">
{{items.text}}
</view>
</view>
</view>
</template>
3、通过每个对象独一无二的id在赋值给activeIndex从而改变月份的样式activeclass:
<style>
.big{
width: 100%;
height: auto;
display: flex;
margin-top: 20rpx;
flex-flow: row wrap;
align-items: flex-start;
background-color: #c9c9c9;
justify-content: space-evenly;
}
.little{ /*点击前的样式*/
display: flex;
width: 225rpx;
height: 120rpx;
margin-top: 20rpx;
align-items: center;
justify-content: center;
background-color: #ffffff;
}
.activeclass{ /*点击后的样式改变*/
color: aquamarine;
background-color: blue;
}
</style>
运行结果:
点击前:
点击其中一个:
原理:
通过tap事件将id的值传入在data中定义的activeIndex索引从而改变盒子的样式id是多少就是那个盒子样式进行改变:class="{activeclass: activeIndex === items.id}"