1. 程式人生 > 程式設計 >Vue實現簡單購物車小案例

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="shttp://www.cppcns.com
tylesheet" href="//index.css" > </head> <body> <div id="app"> <div v-if="books.length != 0ySREcAPQKz"> <table> <thead> <tr> <th></th> <th>書籍名稱</th> <th>出版如期</th> <twww.cppcns.com
h>價格</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> www.cppcns.com
<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="//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:'《計算機基礎》',price:95.00,{
        id:3,name:'《c++高階語言》',price:89.00,{
        id:4,name:'《編譯原理》',price:77.00,]
   
  },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)
    }
  }
})

執行結果

Vue實現簡單購物車小案例

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。