Vue.js实现购物车功能
1.功能实现
以表格的形式将存放在后端的购物信息展示在前端页面,实现步骤如下:
使用axios技术异步读取json文件里的数据,结合Vue.js的v-for指令将信息逐条迭代存放在表格中,在表格中展示“商品名称”、“商品单价”、“商品数量”等信息,并能对商品进行数量的增加、减少,清除此项订单信息的功能,订单总价随着商品数量的增加和减少实时更新。
2.order.json数据如下
[{id:1,name:'华为Mate40',price:7299,count:2},{id:2,name:'iphone XR',price:6199,count:1,},{id:3,name:'小米10',price:3999,count:3}]
3.前端界面如下
<body><div id ="app" ><template v-if="list.length"><table border="1px" style="width: 400px;"><thead><tr><th>编号</th><th>商品名称</th><th>商品单价</th><th>购买数量</th><th>操作</th></tr></thead><tr v-for="(product,index) in list"><td>{{index+1}}</td><td>{{product.name}}</td><td>{{product.price}} </td><td><button @click="subProduct(index)" :disabled="product.count==1">-</button>{{product.count}}<button @click="addProduct(index)">+</button></td><td><button @click="removePriduct(index)">移除</button></td></tr><tbody></tbody></table><div>总金额:¥{{totalPrice}}</div></template><template v-else>购物车为空 </template>
</div>
</body>
4.js代码如下
<script>//创建Vue实例,得到 ViewModelvar app = new Vue({el: '#app',
/*数据*/data: {list:[],
},
/*自动加载函数*/mounted(){//异步读取json文件数据axios.get('/json/order.json',{}).then(response(){app.list=response.data;);
},
/*执行触发函数*/methods: {//数量减少subProduct:function(index){this.list[index].count--;},//数量增加addProduct:function(index){this.list[index].count++;},//清除订单removePriduct:function(index){this.list.splice(index,1);}},
/*动态计算属性*/computed: {//返回总金额totalPrice:function(){var total=0;for (var i=0;i < this.list.length;i++){total+=this.list[i].price*this.list[i].count;}return total;}
},});</script>
效果图如下: