亲宝软件园·资讯

展开

Vue购物车小案例 Vue实现简单购物车小案例

热爱的前端小刘 人气:0
想了解Vue实现简单购物车小案例的相关内容吗,热爱的前端小刘在本文为您仔细讲解Vue购物车小案例的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:vue,购物车,下面大家一起来学习吧。

HTML首页

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="/css/index.css" >
  
</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="(item,index) in books">
          <td>{{item.id}}</td>
          <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="removeHandle(index)">移除</button></td>
        
        </tr>
      </tbody>
    </table>
    <h2>总价格为:{{totalPrice | showPrice}}</h2>
   </div>
   <h2 v-else>购物车为空</h2>
  </div>
 
  <script src="/js/vue.js"></script>
  <script src="/js/index.js"></script>
</body>
</html>

css代码

* {
  margin: 0;
  padding: 0;
}
table {
  margin: 100px 0 0 100px;
  border: 1px solid #e9e9e9;
  border-collapse: collapse;
  border-spacing: 0;
}
 
th,
td {
  padding: 8px 16px;
  border: 1px solid #e9e9e9;
  text-align: left;
}
 
th {
  background-color: #f7f7f7;
  color: black;
  font-weight: 6000 ;
}
 
h2 {
  width: 500px;
  margin-left: 100px;
}
 
button {
  padding: 5px;
}

js代码(Vue)

const app = new Vue({
  el:"#app",
  data:{
    books:[
      {
        id:1,
        name:'《算法导论》',
        date:'2019-2',
        price:85.00,
        count:1
      },
      {
        id:2,
        name:'《计算机基础》',
        date:'2019-2',
        price:95.00,
        count:1
      },
      {
        id:3,
        name:'《c++高级语言》',
        date:'2019-2',
        price:89.00,
        count:1
      },
      {
        id:4,
        name:'《编译原理》',
        date:'2019-2',
        price:77.00,
        count:1
      },
    ]
   
  },
  methods:{
    decrement(index){
      this.books[index].count--
    },
    increment(index){
      this.books[index].count++
    },
    removeHandle(index){
      this.books.splice(index,1)
    }
  },
 
  computed:{
    totalPrice(){
      let finalPrice = 0
      for(let i = 0; i < this.books.length; i++){
        finalPrice +=  this.books[i].price * this.books[i].count
      }
      return finalPrice
    }
  },
 
  filters:{
    showPrice(price){
      return '¥' + price.toFixed(2)
    }
  }
})

运行结果

加载全部内容

相关教程
猜你喜欢
用户评论