原创

Vue小案例(2)

初学Vue 案例二 《虚拟购物车》

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>购物车小案例</title>
    <link rel="stylesheet" href="css/style.css">
    <!--
        购物车小案例
            技术运用:
                v-for
                v-if
                computed
                filter
    -->
</head>
<body>

<div id="app">
    <div v-if="books.length > 0">
        <table>
            <thead>
            <tr>
                <th></th>
                <th>书籍名称</th>
                <th>出版日期</th>
                <th>价格</th>
                <th>购买数量</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="(book,index) in books">
                <td>{{book.id}}</td>
                <td>{{book.name}}</td>
                <td>{{book.date}}</td>
                <td>{{book.price | formatPrice}}</td>
                <td>
                    <button :disabled="book.count == 1" @click="priceReduce(index)">-</button>
                    {{book.count}}
                    <button @click="priceAdd(index)">+</button>
                </td>
                <td><button @click="itemRemove(index)">移除</button></td>
            </tr>
            </tbody>
        </table>
        <h4>总价格{{total | formatPrice}}</h4>
    </div>

    <h3 v-else>暂无数据</h3>
</div>

<script src="../js/vue.js"></script>
<script src="js/main.js"></script>
</body>
</html>

##js部分

const vm = new Vue({
  el: '#app',
  data: {
    books :[
      {id:1,name:'鬼父',date:'2018-05-07',price:60,count:1},
      {id:2,name:'日在校园',date:'2018-05-07',price:40,count:1},
      {id:3,name:'缘之空',date:'2018-05-07',price:30,count:1},
      {id:4,name:'人渣的本源',date:'2018-05-07',price:70,count:1}
    ]
  },
  methods:{
    priceAdd(index){
      this.books[index].count +=1;
    },
    priceReduce(index){
      let count =  this.books[index].count;
      if (count <= 1){
        count = 1;
      }else {
        count--;
      }
      this.books[index].count = count;
    },
    itemRemove(index){
      this.books.splice(index,1);
    }
  },
  //计算属性
  computed:{
    total:function () {
      let total = 0;
      for (let book of this.books){
        total += (book.price * book.count)
      }
      return total;
    }
  },
  //过滤器
  filters:{
    formatPrice(price){
      return '$ ' + price.toFixed(2);
    }
  }
});

Vue
前端

留言板