Vue2.0点击切换类名改变样式的方法
程序员文章站
2022-07-03 20:52:42
1、使用index
1、使用index
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>vue导航</title> <style media="screen"> *{ margin:0; padding: 0; } ul li{ list-style: none; } .navul{ margin:100px auto 20px; overflow: hidden; } .navul li{ background-color: #5597b4; padding:18px 30px; float:left; color: #fff; font-size: 18px; cursor: pointer; } .active{ background-color: #5597b4; } .home .home,.new .new,.contact .contact,.service .service{ background-color: skyblue; } .checked{ background: #eff4f7; } </style> </head> <body> <div id="nav"> <ul> <li v-for="(relation,index) in relations" v-bind:id="relation.id" v-bind:id="relation.id" v-bind:class="{checked:index==nowindex}" v-on:click="relationclick(index)"> <i></i> <span class="">{{relation.text}}</span> </li> </ul> </div> <script src="js/vue.js" charset="utf-8"></script> <script type="text/javascript"> var nav = new vue({ el:'#nav', data:{ relations: [ {text:'项目',id:'program'}, {text:'人员',id:'person'}, {text:'机构',id:'organization'}, {text:'技术',id:'tech'}, {text:'地区',id:'location'}, {text:'国家',id:'country'} ], nowindex:0 // willshow:false }, methods:{ relationclick:function(index){ this.nowindex=index; } } }); </script> </body> </html>
2、通过改变当前值切换类名
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>点击切换</title> <style> .glyphicon-minus{ color:#08f; } .glyphicon-plus{ color:purple; } </style> <script src="js/vue.js"></script> </head> <body> <div id="box"> <div style="width:100px; height:100px; background: #6bacdf;" v-show="isdisplay"></div> <div class="form-group"> <button class="btn" :class="[isshow?'btn-primary':'']" @mouseover="toggleshow()" @mouseout="toggleshow()" v-text="btnstyle"></button> </div> <div class=""> <button class="btn" :class="[istrue?'glyphicon-minus':'glyphicon-plus']" @click="togglebar()">切换类名按钮</button> </div> </div> <script type="text/javascript"> new vue({ el:'#box', data:{ isdisplay:false, isshow: false, istrue:true, btnstyle: 'default' }, methods:{ toggleshow: function() { this.isshow = !this.isshow; }, togglebar:function(){ this.istrue = !this.istrue; } }, watch: { isshow: function(newval) { // console.log(newval); newval ? this.btnstyle = 'primary' : this.btnstyle = 'default' } }, }); </script> </body> </html>
拓展知识:vue点击改变样式的实例
data里
isactive:-1,
method里
checkeditem(index){ this.isactive=index; },
页面里
<div v-for="(item,index) in nameoptions" v-bind:class="{active:index==isactive}" @click="checkitem(index)>{{item.name}}</div>
以上这篇vue2.0点击切换类名改变样式的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
上一篇: TypeScript中类的使用