您的位置:首页 > Web前端 > JQuery

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

2017-04-28 00:00 886 查看
实际项目中,我们会遇到很多类似的需求,一个列表,需要点击其中一条高亮显示。熟悉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;
};
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: