如何用vue.js写简单的购物车(代码教程)
程序员文章站
2022-07-08 14:00:47
利用mock返回假数据
...
利用mock返回假数据
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> table{ border-collapse:collapse; float: left; border:1px solid #999; } #btn{ background:#999; color: #fff; } #shop{ list-style: none; } #shop li{ width: 400px; height:150px; border:1px solid #999; } #shop .p{ width:200px; height:30px; background:gray; color: #fff; text-align: center; line-height:30px; } #shop .p1{ color:orange; float: left; } #shop .p2{ color: #999; float: left; margin-left:10px; } #shop .p3{ clear: both; } </style> <script src="./homework/node_modules/vue/dist/vue.min.js"></script> <script src="./homework/node_modules/axios/dist/axios.min.js"></script> </head> <body> <p id="app"> <ul id="shop"> <li v-for="item,index in plist" :key="item.id" id="li"> <p class="p">{{item.title}}</p> <p class="p1">¥{{item.sprice}}</p> <p class="p2"><del>¥{{item.price}}</del></p> <p class="p3"> <button @click="sub(item)">-</button> <button @click="add(item)">+</button> </p> </li> </ul> <template v-if="car.length"> <table border="1px"> <tr v-for="item,index in car"> <td>{{item.title}}</td> <td> ¥{{item.sprice}} <del>¥{{item.price}}</del> </td> <td> {{item.num}} </td> </tr> </table> <button @click="empty" id="btn">清空购物车</button> </template> </p> <script> //npm install axios安装axios var baseurl="https://www.easy-mock.com/mock/5a167443d8031f24f9a7a5f9/daojia"; //创建Vue实例 var vm = new Vue({ el:"#app", data:{ plist:[],//存放列表数据 car:[], buyed:[] }, methods:{ add:function(item){ if(this.buyed.indexOf(item.id)>=0){//判断商品是否已经添加了 for(var i=0;i<this.car.length;i++){ if(this.car[i].id==item.id){ if(this.car[i].num>item.store){ return ; } this.car[i].num+=1; this.$set(this.car, i, this.car[i]); return; } } return;//结束当前函数别的运行 } item.num = 1; this.buyed.push(item.id); this.car.push(item); }, sub:function(item){ for(var i=0;i<this.car.length;i++){ if(this.car[i].id==item.id){ if(this.car[i].num==1){ this.car.splice(i,1); this.buyed.splice(i,1); return; } this.car[i].num-=1; this.$set(this.car,i,this.car[i]); return; } } }, empty:function(){ this.car=[]; this.buyed=[]; } }, created:function(){ var th = this; //当vue实例化完成使用axios异步请求数据 axios.get(baseurl+'/plists').then(function(res){ th.plist=th.plist.concat(res.data.plists); //console.log(res.data) }).catch(function(err){ console.log(err) }); } }) //创建mock数据 var data = { "list|10-20": [ { "id":"@guid", "title":"@ctitle", "price|1-100.2":0, "sprice":function(){ return this.price-3; }, "store|2-20":1 } ] } </script> </body> </html>