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

示例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>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • HTML 5 HTML5概述 因特网上的信息是以网页的形式展示给用户的,因此网页是网络信息传递的载体。网页文件是用...
    阿啊阿吖丁阅读 4,068评论 0 0
  • 前端开发面试题 <a name='preface'>前言</a> 只看问题点这里 看全部问题和答案点这里 本文由我...
    自you是敏感词阅读 786评论 0 3
  • 在线阅读 http://interview.poetries.top[http://interview.poetr...
    前端进阶之旅阅读 114,832评论 24 450
  • 对一个人最好的就是放下,无论再想念也不会去打扰,终有一天你会明白,原来失去比拥有更踏实。情淡了、 心变了、不爱了,...
    笃学青衿阅读 216评论 0 0
  • 又见完一客户,白璃拖着疲惫的身子回家。在家门口掏钥匙,可是翻遍了包也没有找到。 回忆一下,原来被锁在了家里。只怪自...
    加一11阅读 445评论 6 4