使用vue需要导入这个 我这个是本地js,可以吧vue.js下载导入自己的html,也可以去浏览器上选择vue.js 连接在下方
https://cn.vuejs.org/v2/guide/
<script src= "./vue.js"></script> //这个是导入vue.js
//代码实现页
new Vue({
el:"#app",
data:{
goods:[
{name:'苹果',price:18000},
{name:'香蕉',price:12000},
{name:'西瓜',price:99999},
{name:'葡萄',price:19}
],
carts:[ ]
},
computed:{
//求总数
tocal(){
//用来求出总和
return this.carts.reduce((pre,cur)=>{
return pre + cur.count*cur.price
},0)
}
},
methods:{
addcart(i){
//获取goods里的name值
let cur = this.goods[i].name
//和当前的购物车里的这条数据作对比,如果有这条数据则让count+1
//否则则新push一条数据
let num = this.carts.find(item=>item.name==cur)
if(num){
num.count+=1 //在原有的count 上加1
}else{
this.carts.push({
...this.goods[i],count:1 //吧数组展开向里面添加新属性count:1
})
}
},
//添加数据count
add(i){
this.carts[i].count+=1;
},
sub(i){
if(this.carts[i].count>1){
this.carts[i].count-=1;
}
// shanchu(i){
// this.carts.splice(i,1);
// }
}
}
})
页面实现页
<label for="">搜索</label>
<input type="text">
<button>升序</button>
<button>降序</button>
<ul v-for ="item,index in goods">
<li>{{item.name}}--{{item.price}}--<button @click="addcart(index)" >添加购物车</button></li>
</ul>
<h3>购物车</h3>
<table border="1">
<tr>
<td>商品</td>
<td>单价</td>
<td>个数</td>
<td>总数</td>
<td>操作</td>
<td>删除</td>
</tr>
<tr v-for ="item,j in carts">
<td>{{item.name}}</td>
<td>{{item.price}}</td>
<td>{{item.count}}</td>
<td>{{item.price*item.count}}</td>
<td><button @click="add(j)">+</button><button @click="sub(j)">-</button></td>
<!-- <td><button @click="shanchu">删除</button></td> -->
</tr>
<tr>
<td>总价:{{tocal}}</td>
<!-- <td>style="border:none</td> -->
</tr>
</table>
</div>
效果图如下