使用Vue实现jQuery的切换选中效果

实际项目中,我们会遇到很多类似的需求,一个列表,需要点击其中一条高亮显示。熟悉JQuery的同学说这个太简单了。可以给这个选中的element设置一个active的class。配合Css样式,让active有选中高亮效果。但是谁说一定要用到jQuery呢。

  最近在做的项目中,我尝试脱离JQuery,绕过JQuery,我所接触的大部分项目中好像不使用JQuery无法进行开发一样。它确实给开发者提供了太多便利。以至于大部分web网站都依赖它运行着。据w3Techs统计,JQuery的市场份额高达94.9%,是时候脱离JQuery的束缚了。使用Vue.js更简洁,快速地实现。

  选中效果实现的核心实现逻辑是拷贝一份当前状态作为快照。比对列表的快照当前的唯一索引,如果相同则视为选中。

<div id="app">
  <div class="collection">
    <a href="#!" class="collection-item"
       v-for="gameName in gameNames"
       @click="selected(gameName)"
       :class="{active: activeName == gameName}">{{gameName}}</a>
  </div>
</div>
new Vue({
  el: "#app",
  data: {
    gameNames: ['魔兽世界', '暗黑破坏神Ⅲ', '星际争霸Ⅱ', '炉石传说', '风暴英雄',
      '守望先锋'
    ],
    activeName: ''
  },
  methods: {
    selected: function(gameName) {
      this.activeName = gameName
    }
  }
})
<style> 
    .active { color: #f00;}
</style>  

参考:https://jsfiddle.net/xiaoluoboding/z5xusoL9/

          http://xlbd.me/vue-js-selected-highlight/

 

补充:利用item的index进行判断

<div class="btn-group TP_time_btnBox" role="group">
    <template v-for="(item,index) in topoTime.data">
        <button type="button" class="btn btn-default" @click="switchTab(item,index)" :class="{active3: topoTime.activeIndex == index}">{{item.name}}</button>
    </template>
</div>
.active3{
    background: #35bcff!important;
    color:#fff!important;
    border:1px solid transparent!important;
}
"topoTimeTemp":{
	"activeIndex":0,
	"data":[
		{"name":"现网"},
		{"name":"2017--12"},
		{"name":"2018--12"},
		{"name":"2019--12"}
	]
}
data:{
	topoTime:{}
}

this.$http.get("scripts/e2e_data.json").then(function(res){
	    this.topoTime = res.data.result.topoTimeTemp;
					
	}).catch(function(res){
		console.log(res);
	});

switchTab:function(item,index){
	if(this.slideBarSwitch.activeIndex != index){
		this.slideBarSwitch.activeIndex = index;
	};
}

 

转载于:https://my.oschina.net/u/3288561/blog/889387

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值