先上代码,解析在后方
html部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>购物车</title>
<link rel="stylesheet" href="shopStyle.css">
</head>
<body>
<div id="shop" v-cloak>
<template v-if="list.length">
<table>
<thead>
<tr>
<th></th>
<th>商品名称</th>
<th>商品单价</th>
<th>商品数量</th>
<th>操作</th>
<th>选择</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in list">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.price}}</td>
<td>
<button
@click="handleReduce(index)"
:disabled="item.count === 1">-</button>
{{item.count}}
<button @click="handleAdd(index)">+</button>
</td>
<td>
<button @click="handleRemove(index)">移除</button>
</td>
<td>
<input type="radio" v-model ="selected" :value="item.id">
</td>
</tr>
</tbody>
</table>
<div>选中商品总价:¥{{price}}</div>
<div>购物车商品总价:¥{{totalPrice}}</div>
</template>
<div v-else>购物车为空</div>
</div>
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<script src="indexshop.js"></script>
</body>
</html>
css部分:
[v-cloak] {
display: none;
}
#shop {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
table {
border: 1px solid #333;
border-collapse: collapse;
border-spacing: 0;
empty-cells: show;
}
th,
td {
padding: 8px 16px;
border: 1px solid #e9e9e9;
text-align: left;
}
th {
background-color: #f7f7f7;
color: #5c6b77;
font-weight: 600;
white-space: nowrap;
}
js部分:
var shop = new Vue({
el: "#shop",
data: {
list: [{
id: 1,
name: 'iPhone',
price: '7999',
count: 1
},
{
id: 2,
name: 'iPaid',
price: '9999',
count: 1
},
{
id: 3,
name: 'iWatch',
price: '5999',
count: 1
},
{
id: 4,
name: 'superApple',
price: '199',
count: 1
},
{
id: 5,
name: 'peach',
price: '99',
count: 1
},
{
id: 6,
name: 'car',
price: '1555999',
count: 1
}
],
selected: "2"
},
methods: {
handleReduce: function(index) {
if (this.list[index].count === 1) return;
this.list[index].count--;
},
handleAdd: function(index) {
this.list[index].count++;
},
handleRemove: function(index) {
this.list.splice(index, 1);
}
},
computed: {
totalPrice: function() {
var total = 0;
for (var i = 0; i < this.list.length; i++) {
var item = this.list[i];
total += item.price * item.count;
}
return total.toString().replace(/\B(?= (\d{3})+$)/g, ',');
},
price: function() {
var total = 0;
var item = this.list[Number(this.selected) - 1];
total += item.price * item.count;
return total.toString().replace(/\B(?= (\d{3})+$)/g, ',');
}
}
});
其中在设置每个商品的单选框input组件的value时,需要动态设置,与v-model指令配对,实现单选之后显示当前的选中的商品的价格,所以采用:value=""的形式动态更新获取,js部分利用商品的id即selected的值来获取到单选之后的商品价格即
var item = this.list[Number(this.selected) - 1];
total += item.price * item.count;
这两句很关键,通过id找到list的索引进行计算