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的进阶

结果图:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值