8-Vue基礎階段小案例

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>購物車案例</title>
  <style>
    th,td{
      border:1px solid red
    }

  </style>
</head>
<body>

 <div id="app">
   <div v-if="books.length!=0">
     <table>
       <thead>
       <tr>
         <th>序號</th>
         <th>書籍名稱</th>
         <th>書記價格</th>
         <th>書籍數量</th>
         <th>操作</th>
       </tr>
       </thead>
       <tbody>
       <tr v-for="(book,index) in books" >
         <td>{{index+1}}</td>
         <td>{{book.name}}</td>
         <td>{{book.price | show}}</td>
         <td>
           <button @click="decrement(index)" :disabled="book.number<=1">-</button>
           {{book.number}}
           <button @click="increment(index)">+</button>
         </td>
         <td><button @click="remove(index)">移除</button></td>
       </tr>
       </tbody>
     </table>
     <h2>總價格:{{totalPrice | show}}</h2>
   </div>
   <span v-else>購物車爲空</span>


 </div>

   <script src="js/vue.js"></script>
   <script>
     let app = new Vue({
       el: '#app',
       data: {
         message: 'HelloWorld',
         books:[
           {
             id:1,
             name:'Linux',
             price:40.00,
             number:1
           },
           {
             id:2,
             name:'Java',
             price:50.00,
             number:1
           },
           {
             id:3,
             name:'C++',
             price:30.00,
             number:1
           }
         ]
       },
       methods:{
          increment(index){
            this.books[index].number++;
          },
         decrement(index){
            this.books[index].number--;
         },
         remove(index){
            this.books.splice(index,1)
         }
       },
       //過濾器,處理價格顯示
       filters:{
         show(price){
           return '¥'+price.toFixed(2);
         }

       },
       computed:{
         totalPrice(){
           // let result=0;
           // for(let book of this.books){
           //   result += book.price * book.number;
           // }
           // return result;
           
           // for的進階
           return this.books.reduce(function (preva,cur) {
             return preva + cur.price * cur.number;
           },0)
         }
       }
     });
   </script>
</body>
</html>

上述新增了過濾器+按鈕的禁用+for的進階

結果圖:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章