美文网首页
vue实现点击后动态添加class及删除同级class

vue实现点击后动态添加class及删除同级class

作者: 一名有马甲线的程序媛 | 来源:发表于2018-03-14 09:44 被阅读351次
示例1

大体思路:声明一个初始变量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,要如何做呢~


示例2

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>

相关文章

网友评论

      本文标题:vue实现点击后动态添加class及删除同级class

      本文链接:https://www.haomeiwen.com/subject/wyixqftx.html