利用Vue的v-for和v-bind實現列表顏色切換
需求:
在頁面上顯示四個列表,初始時字體為黑色。
鼠標點擊某一個列表時,該列表的顏色變為紅色,其余列表仍為黑色。
代碼實現:
<!-- css --><style> .red{ color: red; }</style><!-- html --><div id='app'> <ul> <li v-for='item,index in movies' : v-on:click='change(index)'>{{item}}</li> </ul></div><!-- JavaScript --><script src='http://www.cgvv.com.cn/JS/vue.js'></script><script> const app = new Vue({ el: ’#app’, data: { movies: [’肖申克的救贖’,’泰坦尼克號’,’當幸福來敲門’,’流浪地球’], changeRed: -1 }, methods: { change:function (index) { this.changeRed=index; } } })</script>
代碼解釋:
首先瀏覽器直接顯示列表,因為此時沒有監聽到click事件。
當鼠標點擊某一個列表時,Vue自動獲取列表下標,并執行change(index)函數,改變changeRed的值,此時當前列表的v-bind:class='{red: changeRed == index}'中的red為true,當前一項列表顯示為紅色。其余列表的changeRed == index為false,所以不顯示紅色。
補充知識:vue學習(綁定class、v-bind:style(對象語法、數組語法))
vue 屬性綁定
css
.class0{ color: red; font-size: 10px; } .class00{ color: blue; font-size: 70px; } .class2{ color: yellow; font-size: 30px; } .class3{ color: indianred; } .class4{ font-size: 30px; }
1 class綁定
1.1 字符串綁定
<div id='app1'> 可以綁定一個默認class 字符串綁定class <p :class='a'> xxxx是字符串 </p> <button @click='updates1'> 點擊</button></div>
// 1.1 字符串綁定 var a = new Vue({ el:’#app1’, data: { //綁定默認css屬性 a: 'class1', b:'class0', }, //動態切換css屬性 methods: { updates1 (){ this.a = ’class2’ } } });
1.2 對象綁定 和 數組綁定
<div id='app2'> 對象綁定class <p :class='{class2:isA,class00:isB}'> xxxx是對象 例如 :class='{class2:isA,class00:isB}'</p> <button @click='updates2'> 點擊</button> <br> 數組綁定class <br> <p :class='[’class3’,’class4’]'> xxxx是數組 例如 : </p></div>
//1.2 對象綁定 var a = new Vue({ el:’#app2’, data: { //綁定默認css屬性 isA: true, isB: false, }, //動態切換css屬性 methods: { updates2 (){ this.isA = false; this.isB = true; } } });
圖示
點擊后
2 style 綁定
<div id='app3'> <div :style='{ color: activeColor, fontSize: fontSize + ’px’ }'>Style 綁定1 例如 :style='{ color: activeColor, fontSize: fontSize + ’px’ }'</div> <div :style='objectCssStyle'>Style 綁定2(綁定到一個樣式對象通常更好) 例如 :style='objectCssStyle'</div> <div :style='[clSty1, clSty2]'>Style 綁定3(數組語法) 例如 :style='[activeColor, fontSize]'</div> <button @click='updates4'> 點擊</button></div>
// 2 style 綁定 var a = new Vue({ el:’#app3’, data: { //綁定默認css屬性 activeColor: ’red’, fontSize: 100, objectCssStyle:{ color: ’red’, fontSize: ’10px’ }, objectCssStyle2:{ color: ’yellow’ }, clSty1: { color: ’green’, fontSize: ’30px’ }, clSty2: { ’font-weight’: ’bold’ } }, //動態切換css屬性 methods: { updates4 (){ this.activeColor = 'blue'; this.fontSize = 20; this.objectCssStyle = this.objectCssStyle2 } } });
圖示
點擊后
以上這篇利用Vue的v-for和v-bind實現列表顏色切換就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章: