vue.js购物车

时间:2023-03-09 13:08:49
vue.js购物车

vue.js

https://cn.vuejs.org/v2/guide/

简单购物车

<html>

<head>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<style>
table {
border: 1px solid black;
} table {
width: 100%; border-spacing: 0;
} th {
background-color: #ddd;
} th,
td {
border-bottom: 1px solid #ddd;height: 50px;text-align:center;
} .red {
color: red
} .green {
color: green
}
</style>
</head> <body>
<div id="app">
<table>
<tr>
<th>序号</th>
<th>商品名称</th>
<th>商品价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
<tr v-for="iphone in PJson">
<td>{{ iphone.id }}</td>
<td>{{ iphone.name }}</td>
<td class="red">¥{{ iphone.price }}</td>
<td>
<button v-bind:disabled="iphone.count == 1" v-on:click="iphone.count-=1" v-bind:class="{green:iphone.count>1,red:iphone.count==1}">-</button>
{{ iphone.count }}
<button v-bind:disabled="iphone.count == 9" v-on:click="iphone.count+=1" v-bind:class="getBtnClass(iphone.count)">+</button>
</td>
<td>
<button v-on:click="del($index)">移除</button>
</td>
</tr>
</table>
<p>
说明:满100包邮,每个商品限购9件
</p>
<p>
<span class="red">总价:¥{{totalPrice()}}</span>
<span class="green" v-if="totalPrice()>0" v-show="youfei>0">(含邮费¥{{youfei}})</span>
<span class="green" v-show="youfei==0">(包邮)</span>
</p> </div> <script>
var app = new Vue({
el: '#app',
data: {
youfei: 10,
PJson: [
{
id: 1,
name: 'iphone1',
price: 10,
count: 1
},
{
id: 2,
name: 'iphone2',
price: 20,
count: 1
},
{
id: 3,
name: 'iphone3',
price: 30,
count: 1
}] },
computed: {
//写在methods里也可以的
getBtnClass(){
return function(num)
{
return{green:num<9,red:num==9}
}
}
},
/*computed: {
youhui:function(){
return 100
}
},*/
methods: {
del: function (ii) {
this.PJson.splice(ii, 1);
},
totalPrice: function () {
var totalP = 0;
for (var i = 0, len = this.PJson.length; i < len; i++) {
totalP += this.PJson[i].price * this.PJson[i].count;
}
if (totalP >= 100) {
this.youfei = 0
} else {
this.youfei = 10
}
if (totalP > 0) {
return totalP + this.youfei;
}
return 0;
},
getBtnClass2:function(num)
{
return{green:num<9,red:num==9}
} }
})</script>
</body> </html>