Vue 條件判斷和迴圈判斷
阿新 • • 發佈:2020-11-06
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> <labelfor="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 遍歷 陣列、物件
v-for 遍歷陣列
能做到響應式的方法
【push()最後面新增、pop()刪除最後一個、shift()刪除第一個、unshift()最前面新增、splice()刪除/插入/替換元素、sort()排序、reverse()反轉】
(,,,num 可變引數寫法)
不能做到響應式的方法
通過索引值修改陣列的元素: this.num[0] = "aaa" 不會生效
解決辦法:set(要修改的物件,索引,修改後的值)
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>