<!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>
</head>
<script src="js/vue221.js"></script>
<body>
<div id="app">
<table border="1" cellspacing="0">
<tr>
<th>商品名称</th>
<th>商品单价</th>
<th>商品数量</th>
<th>小计</th>
</tr>
<tr v-for="(item,index) in goodsList">
<td>
{{item.name}}
</td>
<td>
{{item.price}}
</td>
<td>
<button @click="reduceCount(index)">-</button>
{{item.count}}
<button @click="addCount(index)">+</button>
</td>
<td>
{{item.count*item.price}}
</td>
</tr>
<tr>
<td>
总数量:
</td>
<td>
{{totalCount}}
</td>
<td>
总价格:
</td>
<td>
{{totalPrice}}
</td>
</tr>
</table>
</div>
</body>
<script>
//商品: 名称 单价 数量
//使用对象来进行存储 {name:"篮球鞋",price:500,count:1}
//总数量不是固定数据,根据每一个商品的数量 运算得出的 在vue中 属于计算属性
//计算属性 :通过计算 得出新的属性
let vm=new Vue({
el:"#app",
data:{
goodsList:[
{name:"篮球鞋",price:500,count:1},
{name:"队服",price:200,count:3},
{name:"电脑",price:5000,count:2}
]
},
methods:{
addCount(index){
//找到对应的对象 将其count++
this.goodsList[index].count++
},
reduceCount(index){
if(this.goodsList[index].count>0){
this.goodsList[index].count--
}
}
},
computed:{
//定义一个新的名称
totalCount(){
//依次拿出数组中的每个商品对象让其求和
let sum = 0
for(let n = 0;n<this.goodsList.length;n++){
sum=sum+this.goodsList[n].count
}
return sum
},
totalPrice(){
let sum=0
for(let n=0;n<this.goodsList.length;n++){
sum=sum+this.goodsList[n].price*this.goodsList[n].count
}
return sum
}
}
})
</script>
</html>
购物车案例(vue)
最新推荐文章于 2024-02-07 18:04:53 发布