1.v-if v-else-if v-else
2.小問題
用戶登錄案例<br> <span v-if ="isUser"> <label for="username">用戶賬號:</label> <input type="text" id="username" placeholder="用戶賬號" key="username"> </span> <span v-else> <label for="useremail">用戶郵箱:</label> <input type="text" id="useremail" placeholder="用戶郵箱" key="useremail"> </span> <button @click="isUser = !isUser">切換用戶</button>
提醒:因為Vue底層會渲染虛擬DOM,所以如果input中有值不會因為‘切換用戶’清空。
解決:在input上添加key,並且key值不同
3.v-show 會顯示dom,改變display的值
4.v-for 遍歷 數組、對象
1.v-for 遍歷數組
當遍歷的數據需要中間修改修改時候,我們添加一個key值,可根據diff算法,優化性能。
(例:<li v-for=“item in nums” :key="item">{{item}}</li>)這里的key要是用item和顯示內容一致,並且item在nums中屬於唯一值。
2.響應式的方法
push()最后面添加一個或多個、
pop()刪除最后一個
shift()刪除第一個
unshift()最前面添加
splice()刪除/插入/替換元素
sort()排序
reverse()反轉
不能做到響應式的方法
通過索引值修改數組的元素: this.num[0] = "aaa" 不會生效
Vuede set()解決辦法:set(nums, index, item)(要修改的對象,索引,修改后的值)
5.filters: 過濾器
6.實戰案例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>VUE</title> <style> .active{color:red} td{padding:15px;} </style> </head> <body> <div id="app"> <div v-if="books.length"> <table> <thead> <tr> <th></th> <th>書籍名稱</th> <th>出版日期</th> <th>價格</th> <th>購買數量</th> <th>操作</th> </tr> </thead> <tbody> <tr v-for="(item,index) in books"> <td>{{item.id}}</td> <td>{{item.name}}</td> <td>{{item.date}}</td> <td>{{item.price | finalPrice}}</td> <td> <button @click="subtract(index)" v-bind:disabled="item.count <= 1">-</button> {{item.count}} <button @click="add(index)">+</button> </td> <td> <button @click="removerHandler(index)">移除</button> </td> </tr> </tbody> </table> <h2>總價格:{{totaPrice | finalPrice}}</h2> </div> <h2 v-else>購物車為空</h2> </div> <script src="js/vue.js"></script> <script> const app = new Vue({ el:"#app", data: { books:[ {id:1,name:'數學',date:'2006-9',price:85.00,count:1}, {id:2,name:'語文',date:'2011-9',price:59.00,count:1}, {id:3,name:'英語',date:'2015-9',price:6.00,count:1}, {id:4,name:'物理',date:'2005-9',price:82.00,count:1}, {id:5,name:'化學',date:'2008-9',price:128.00,count:1} ] }, computed:{ totaPrice(){ let totaPrice = 0 for ( let i in this.books){ totaPrice += this.books[i].price * this.books[i].count } return totaPrice } }, methods: { subtract(index){ this.books[index].count-- }, add(index){ this.books[index].count++ }, removerHandler(index){ this.books.splice(index,1) } }, filters: { finalPrice(price){ return "¥" + price.toFixed(2) } } }) </script> </body> </html>