Vue图书购物车小案例

html文件:

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Document</title>

    <link rel="stylesheet" href="style.css">

</head>

<body>

    <div id="app">

      <table v-if="books.length">

        <thead>

          <tr>

            <th>书籍名称</th>

            <th>出版日期</th>

            <th>价格</th>

            <th>购买数量</th>

            <th>操作</th>

          </tr>

        </thead>

        <tbody>

          <tr v-for="(item, index) in books">

            <td>{{item.name}}</td>

            <td>{{item.date}}</td>

            <td>{{item.price | showPrice}} </td>

            <td>

              <button @click='decrement(index)' :disabled="item.count == 1">-</button>

              {{item.count}}

              <button @click='increment(index)'>+</button>

            </td>

            <td>

              <button @click="removeHander(index)">移除</button>

            </td>

          </tr>

        </tbody>

      </table>

      <h2 v-else>购物车为空</h2>

      <h2>{{finalPrice | showPrice}}</h2>

    </div>

    <!-- 框架js放前面 -->

    <script src="../../../js/vue.js"></script> 

    <script src="main.js"></script>

</body>

</html>    

js:

const app = new Vue({

  el: '#app',

  data: {

    books: [

      {

      id: 1,

      name:'《算法导论》',

      date: '2006-9',

      price: 85.00,

      count: 1

      },

      {

        id: 2,

        name:'《计算机操作系统》',

        date: '2003-7',

        price: 99.00,

        count: 1

      },

      {

        id: 3,

        name:'《代码大全》',

        date: '2006-2',

        price: 128.00,

        count: 1

      },

      {

        id: 4,

        name:'《Java入门》',

        date: '2014-2',

        price: 80.00,

        count: 1

      },

    ]

  },

  filters: {

    showPrice(price){

      return '¥' + price.toFixed(2)

    }

  },

  methods: {

    increment(index) {

      this.books[index].count++

    },

    decrement(index) {

      this.books[index].count--

    },

    removeHander(index) {

      this.books.splice(index, 1)

    }

  },

  computed: {

    finalPrice() {

      let totalPrice = 0;

      // for(let p in this.books){

      //   totalPrice+= p.count * p.price;

      // }

      for(let i = 0; i < this.books.length; i++) {

        totalPrice += this.books[i].price *this. books[i].count

      }

      return totalPrice

    }

  }

})

效果:

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容