1. 程式人生 > 實用技巧 >vue監聽購物車數量變化及實現模糊查詢

vue監聽購物車數量變化及實現模糊查詢

要點:使用過濾器和計算屬性

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>vue監聽購物車數量及模糊查詢</title>
    <script src="vue.js"></script>
  <!-- 引入樣式 -->
  <link rel="
stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"> <script src="https://unpkg.com/element-ui/lib/index.js"></script> </head> <body> <div id="app"> <div style="margin: 10px 0;"> <label>名稱搜尋:</label> <input v-model="
searchInput" type="text" placeholder="請輸入查詢內容" style="width:300px;padding: 5px;"> </div> <el-table :data="searchData" border style="width: 100%"> <el-table-column label="圖片"> <template slot-scope="scope"> <img :src="scope.row.url
"> </template> </el-table-column> <el-table-column prop="name" sortable label="商品名稱"> </el-table-column> <el-table-column sortable label="商品數量"> <template slot-scope="scope"> <input value="-" @click="scope.row.count-=1" :disable="scope.row.count<=0" /> <span>{{scope.row.count}}</span> <input value="+" @click="scope.row.count+=1" :disable="scope.row.count<=10" /> </template> </el-table-column> <el-table-column prop="price" sortable label="商品單價"> </el-table-column> <el-table-column sortable label="商品金額"> <template slot-scope="scope"> <span>{{scope.row.count*scope.row.price | priceFilter(3)}}</span> </template> </el-table-column> <el-table-column prop="" sortable label="操作"> <template> <el-button>商品詳情</el-button> </template> </el-table-column> </el-table> <div>{{totalCount}}件商品總計(不含運費):¥{{totalAmount}}</div> </div> <script type="text/javascript"> var vm = new Vue({ el: "#app", data:{ searchInput:'', items:[{ name:'蘋果',price:10,count:10,url:'./images/unlock.png' },{ name:'車釐子',price:34,count:2,url:'./images/unlock.png' },{ name:'火龍果',price:30,count:3,url:'./images/unlock.png' },{ name:'桃子',price:20,count:10,url:'./images/unlock.png' }] }, filters:{ // 過濾器,文字格式化 priceFilter:function(data,n){ return ''+data.toFixed(n) // 保留2位小數 } }, computed:{ // 計算屬性 searchData:function(){ var self =this // filter() 篩選 // 現在輸入文字之後沒有查到結果,因為this的指向不對,在回撥函式和定時器中this的指向是window if (!this.searchInput) return this.items; return this.items.filter(function(item){ return item.name.indexOf(self.searchInput)!=-1 }) }, totalCount:function(){ // var n=0; // this.items.forEach(function(item,index){ // n+=item.count // }); // return n; // 換一種寫法,將這裡的items換成searchData,因為當我們查詢了指定的水果之後,總計的數量和金額也要顯示當前查詢的 return this.searchData.reduce(function(total,cur){ return total+cur.count },0) //0 表示初始化的值 }, totalAmount:function(){ return this.searchData.reduce(function(total,cur){ return total+cur.count*cur.price },0) } } }) // 陣列的reduce方法:var arr =[1,2,3,1,2,5] // var a =arr.reduce(function(total,cur){ // return total+cur // },10) 10是初始值,表示在10的基礎上相加 // total就是前面所加的和,cur指當前的陣列值 // 模糊查詢前端可以做,但是如果資料是分頁展示的,建議後端做模糊查詢,因為每次點選頁碼來展示資料的時候,是向後端介面傳參,然後返回資料,前端做模糊查詢的話是在所有資料都有的情況下做模糊查詢 </script> </body> </html>