vue實作購物車功能
🍅程式員小王的博客:程式員小王的博客
🍅 歡迎點贊 👍 收藏 ?留言 📝
🍅 如有編輯錯誤聯系作者,如果有比較好的文章歡迎分享給我,我會取其精華去其糟粕
🍅java自學的學習路線:java自學的學習路線
原理分析和實作
注意想實作該功能,需要學習:Vue學習之路(基礎篇),深入的了解每個指令的使用
首先,還是先把布局寫好,和引入vue,準備vue實體,這個不多說,代碼如下
<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>vue實作購物車</title>
</head>
<body>
<div id="app">
<h3>購物車</h3>
名稱:<input style="width:60px" type="text" v-model="nameValue"> <br/>
單價:<input style="width:60px" type="text" v-model="priceValue"> <br/>
數量:<input style="width:60px" type="text" v-model="countValue">
<button @click="add()">添加購物車</button>
<hr/>
<table border="1">
<tr>
<td>名稱</td>
<td>單價</td>
<td>數量</td>
<td>小計</td>
</tr>
<tr v-for="(product,index) in products">
<td>{{product.name}}</td>
<td>{{product.price}}</td>
<td>
<button @click="desc(index)">-</button>
{{product.count}}
<button @click="incr(index)">+</button>
</td>
<td>{{product.price*product.count}}</td>
</tr>
<tr>
<td colspan="4">總價:{{total()}}元</td>
</tr>
</table>
</div>
</body>
</html>
<script src="js/vue-min.js"></script>
<script>
new Vue({
el: "#app",
data: {
products: [
{name: "秋褲", price: "81", count: 2},
{name: "華為", price: "5810", count: 1},
],
nameValue: "",
priceValue: "",
countValue: 0,
totalPrice:0
},
methods: {
incr(index) {
this.products[index].count++;
},
desc(index) {
this.products[index].count--;
},
add() {
this.products.push({name: this.nameValue, price: this.priceValue, count: this.countValue});
this.nameValue = "";
this.priceValue = "";
this.countValue = 0;
},
total(){
var price=0;
for (var i = 0; i <this.products.length; i++) {
price+=this.products[i].price * this.products[i].count
}
return price.toFixed(2);
}
}
})
</script>

轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/382005.html
標籤:其他
上一篇:Vue ElmentUI message組件customClass使用方法
下一篇:Vue學習之路(基礎篇)
