1. v-bind的基本使用
在開發的時候,有時候我們的屬性不是寫死的,有可能是根據我們的一些數據動態地決定的,比如圖片標簽(<img>)的src屬性,我們可能從后端請求了一個包含圖片地址的數組,需要將地址動態的綁定到src上面,這時就不能簡單的將src寫死。還有一個例子就是a標簽的href屬性。這時可以使用v-bind指令:
作用:動態綁定屬性;
縮寫(語法糖):: (只用一個冒號代替);
預期:
(1)any (with argument),任意參數;
(2)Object (without argument),對象 。
參數:attrOrProp (optional)
例子1:其中,v-bind可以縮寫成:
服務器請求過來的數據,我們一般都會在data那里做一下中轉,做完中轉過后再把需要的變量綁定到對應的屬性上面。
2. v-bind動態綁定屬性class
v-bind除了在開發中用在有特殊意義的屬性外(src, href等),也可以綁定其他一些屬性,如class。
例子:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <style> 7 .active { 8 color: red; 9 } 10 </style> 11 </head> 12 <body> 13 <div id="app"> 14 <h2 class="title" v-bind:class="{active: isActive, line: isLine}">{{message}}</h2> 15 <h2 class="title" v-bind:class="['active', 'line']">{{message}}</h2> 16 <h2 class="title" v-bind:class="getClassesArray()">{{message}}</h2> 17 18 <button v-on:click="btnClick">按鈕</button> 19 </div> 20 21 <script src="../js/vue.js"></script> 22 <script> 23 const app = new Vue({ 24 el: '#app', 25 data: { 26 message: '你好啊', 27 active: 'active', 28 line: 'line', 29 isActive: true, 30 isLine: true, 31 }, 32 methods: { 33 btnClick: function () { 34 this.isActive = !this.isActive; 35 }, 36 getClasses: function () { 37 return {active: this.isActive, line: this.isLine}; 38 }, 39 getClassesArray: function () { 40 return [this.active, this.isLine]; 41 } 42 } 43 }); 44 </script> 45 </body> 46 </html>
打開的效果:
點擊按鈕之后,效果如下:
這個按鈕的作用就是取反。
3. 練習作業
動態綁定的一個小作業,需求是:點擊列表中的哪一項,那么該選項的文字變成紅色,背景變為淺灰色。直接貼上代碼:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <style> 7 .active { 8 color: red; 9 background-color: lightgray; 10 } 11 </style> 12 </head> 13 <body> 14 <div id="app"> 15 16 <ul> 17 <li v-for="(item, index) in movies" v-on:click="changeColor(index)"> 18 <div v-bind:class="{active: currentIndex == index}">{{index}}-{{item}}</div> 19 </li> 20 </ul> 21 22 </div> 23 24 <script src="../js/vue.js"></script> 25 <script> 26 const app = new Vue({ 27 el: '#app', 28 data: { 29 message: '你好啊', 30 movies: ['海王', '海爾兄弟', '火影忍者', '進擊的巨人'], 31 currentIndex: Number.MIN_VALUE, 32 }, 33 methods: { 34 changeColor: function (index) { 35 this.currentIndex = index; 36 } 37 } 38 }); 39 </script> 40 </body> 41 </html>
博客日常記錄我的學習內容,如果有錯誤歡迎指出。