Vue第三篇:最简单的vue购物车示例

本文参考:Vue Cli(脚手架)实现购物车小案例 - - php中文网博客

 效果图:

编写流程:

1、首先通过@vue/cli创建工程

vue create totalprice

2、改写App.vue代码如下:

<template>
  <div>
    <div v-if="cartlist.length <= 0">你没有选择的商品,购物车为空,去购物</div>
    <table v-else>
      <caption>    <!--表格标题-->
        <h1>购物车</h1>
      </caption>
      <tr>
        <th>选中</th>
        <th>编号</th>
        <th>商品名称</th>
        <th>商品价格</th>
        <th>购买数量</th>
        <th>操作</th>
      </tr>
      <tr v-for="(item, index) in cartlist" :key="item.id">
        <td><input type="checkbox" v-model="item.checkbox"></td>
        <td>{
   
   { item.id }}</td>
        <td>{
   
   { item.name }}</td>
        <td><small>¥</small>{
   
   { item.price.toFixed(2) }}</td>
        <td>
          <button @click="item.count--" :disabled="item.count <= 1">-</button>
          {
   
   { item.count }}
          <button @click="item.count++">+</button>
        </td>
        <td><button @click.prevent="del(index)">删除</button></td>
      </tr>
      <tr>
        <td colspan="3" align="center">总价</td>
        <td colspan="3" align="center">{
   
   { totalPrice }}</td>
      </tr>
    </table>
  </div>
</template>

<script>
  export default {
    name: 'app',
    data(){
      return{
        cartlist:[{
          id: 1,
          checkbox: true,
          name: '《细说PHP》',
          price: 10,
          count: 1
        },{
          id: 2,
          checkbox: true,
          name: '《细说网页制作》',
          price: 10,
          count: 1
        },{
          id: 3,
          checkbox: true,
          name: '《细说JavaScript语言》',
          price: 10,
          count: 1
        },{
          id: 4,
          checkbox: true,
          name: '《细说DOM和BOM》',
          price: 10,
          count: 1
        },{
          id: 5,
          checkbox: true,
          name: '《细说Ajax与jQuery》',
          price: 10,
          count: 1
        },{
          id: 6,
          checkbox: true,
          name: '《细说HTML5高级API》',
          price: 10,
          count: 1
        }
        ]
      }
    },
    methods:{
      del(index){
        this.cartlist.splice(index, 1)
      }
    },
    computed:{
      totalPrice(){
        let sum = 0;
        for(let book of this.cartlist){
          if(book.checkbox){
            sum += book.price * book.count;
          }
        }
        return '¥' + sum.toFixed(2)
      }
    }
  }
</script>

<style scoped>
  table{
    width: 600px;
    border: 1px solid #888888;
    border-collapse: collapse;
  }

  th{
    background-color: #ccc;
  }

  td,th{
    border: 1px solid #888888;
    padding: 10px;
  }

</style>

3、代码中相关内容说明:

(1)<caption>为table的标题

(2)在组件中使用v-for时,必须添加:key属性,否则会报错,为了性能考虑

(3)colspan属性,表示某个td横跨的列数

(4)splice()函数用于从当前数组中移除一部分连续的元素。参数包括start和deleteCount。

(5)border-collapse,折叠样式

猜你喜欢

转载自blog.csdn.net/benben044/article/details/131794475