思路:
第一步:排版:(循环遍历)
<template>
<view>
<!-- 点击切换盒子的颜色(循环遍历型) -->
<view class="study">
<view class="item" v-for="(item,index) in list" >
//index就是每一个的索引,就是相当于每一个盒子的id
{{item.title}}
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
active:'', //点击以后切换
list: [{
title: '第一盒子',
},
{
title: '第二盒子',
},
{
title: '第三盒子',
},
]
}
},
onLoad() {
},
methods: {
}
}
</script>
第二步:设置点击以后的样式
.active {
background-color: #007AFF;
}
第三步: 设置变量,用来储存当前点击的元素
<script>
export default {
data() {
return {
active:'' // 0为默认第一个子盒子,所以要取其他值,或者直接''
}
},
onLoad() {
},
methods: {
}
}
第四步:写点击事件,传入实参
<template>
<view>
<!-- 点击切换盒子的颜色(循环遍历型) -->
<view class="study">
<view class="item" v-for="(item,index) in list"
@click="getother(index)"
:class="{active:index === active }">
//index就是每一个的索引,就是相当于每一个盒子的id
{{item.title}}
</view>
</view>
</view>
</template>
第五步:在method里面,用一个形参变量来接收我们的实参
methods: {
getother(index) {
//这个index就是用来接收我们前面的实参index(就是索引),
所以现在它里面就拿到每一个盒子的id了
this.active= index; // // 把当前点击元素的index,赋值给active
}
}
第六步:再写追加样式
:class="{active:id(盒子的id) === 变量 }"
<!-- 点击切换盒子的颜色(循环遍历型) -->
<view class="study">
<view class="item" @click="getother(index)" v-for="(item,index) in list"
:class="{active:item.index === active}">
{{item.title}}
</view>
</view>
源码展示:
<template>
<view>
<!-- 点击切换盒子的颜色(直接标签) -->
<view class="study">
<view class="item" @click="getpage(1)" :class="{active:1 === num }">
第一个盒子
</view>
<view class="item" @click="getpage(2)" :class="{active:2 === num }">
第二个盒子
</view>
<view class="item" @click="getpage(3)" :class="{active:3 === num }">
第三个盒子
</view>
</view>
<!-- 点击切换盒子的颜色(循环遍历型) -->
<view class="study">
<view class="item" @click="getother(index)" v-for="(item,index) in list"
:class="{active:index === activeClass }">
{{item.title}}
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
num: 0,
activeClass:'',
list: [{
title: '第一盒子',
},
{
title: '第二盒子',
},
{
title: '第三盒子',
},
]
}
},
onLoad() {
},
methods: {
getpage(index) {
this.num = index;
},
getother(index) {
this.activeClass = index;
}
}
}
</script>
<style lang="scss">
.study {
width: 700rpx;
height: 200rpx;
margin: 40rpx auto;
display: flex;
justify-content: space-between;
}
.item {
color: #FFFFFF;
width: 200rpx;
height: 200rpx;
background-color: #F0AD4E;
}
.active {
background-color: #007AFF;
}
</style>
效果显示: