大体思路:声明一个初始变量currentIndex,为0 就是第一个,为1就是第二个默认显示。点击的时候传入的currentIndex=index
html:
<template lang="html">
<div>
<div
@click="changeIndex(index)"
v-for="(item,index) in arr"
:class="{on:currentIndex===index}">
{{item}}
</div>
</div>
</template>
js:
<script>
export default {
data(){
return {
arr:["aa","bb","cc"],
currentIndex:0
}
},
methods:{
changeIndex(index){
this.currentIndex=index;
}
}
}
</script>
css:
<style scoped>
.on{
color: red;
}
</style>
延伸拓展:
同样道理的,点击父级,改变对应子集的class,要如何做呢~
html:
<template lang="html">
<div>
<div class="pay-method"
v-for="(payChannel,index) in payChannels"
v-show="index<3"
@click="SelectChannelType(index)">
<div class="pay-method-box">
<div class="method-left">
<img :src="'../../static/img/'+payChannel.img+'.png'" class="method-img">
<div class="method-box">
<p>{{payChannel.title}}
<img src="../../static/img/recommend.png" :class="{'recommend' : payChannel.recommend }">
</p>
<p class="method-warning" :class="{'warning' : payChannel.warning }">推荐安装微信5.0及以上版本的用户使用</p>
</div>
</div>
<div class="method-right">
<i class="iconfont " :class="index != currentIndex ? 'icon-radio' : 'icon-radioSelected' "></i>
<!-- icon-radio:未选状态 icon-radioSelected:选中状态 -->
</div>
</div>
</div>
</div>
</template>
注意:由于是循环,所以在最外层要套个<div>
js:
<script>
export default {
data () {
return {
payChannels:[
{ img:'pay-wx',recommend:true,title:'微信支付',warning:true},
{ img:'pay-zfb',recommend:false,title:'支付宝支付',warning:false},
{ img:'pay-ysf',recommend:false,title:'云闪付',warning:false},
{ img:'pay-ysf',recommend:false,title:'云闪付',warning:false}
],
currentIndex:0
}
},
methods:{
SelectChannelType(index){
this.currentIndex=index;
}
}
}
</script>