先上结果图:
1.规划主要功能:增加/减少商品数量,删除商品,计算单件商品总金额,根据勾选项结算总价格,全选/取消全选
2.简单写了一下布局,略过。
3.从数据库里读取数据渲染到页面中。但还没学怎么从数据库读取数据,暂时自己定义一个json,从下面这个json中读取数据。
var shoplist = {
"shop":[{
shopname:"剃须刀",
num:2,
onePrice:1000,
check:true
},
{
shopname:"背包",
num:4,
onePrice:200,
check:true
},
{
shopname:"女装长裤",
num:1,
onePrice:170,
check:true
},
{
shopname:"女装大佬上衣",
num:3,
onePrice:300,
check:false
}]
}
html渲染数据:(值得一提的是checked属性,因为要根据勾选项结算总价格,实际上checkbox选中功能不会存到数据库,所以在json数据中定义了check属性,通过改变check的值从而计算总价)
<tbody>
<tr v-for="(v,i) in shopmsg">
<td class="select"><input type="checkbox" :checked="v.check" @click="v.check = !v.check"></td>
<td>{{v.shopname}}</td>
<td class="num">
<span class="op" @click="sub(i)">-</span>
<span class="number" v-model="shopmsg[i].num">{{v.num}}</span>
<span class="op" @click="add(i)">+</span>
</td>
<td>{{'¥'+v.onePrice}}</td>
<td>{{'¥'+v.onePrice*v.num}}</td>
<td class="del" @click="del(i)">删除</td>
</tr>
</tbody>
4.写功能:
new Vue({
el:'#box',
data:{
shopmsg:shoplist.shop,
},
methods:{
add(a){//增加
this.shopmsg[a].num++;
},
sub(a){//减少
if(this.shopmsg[a].num>1){//判断是否为1,如果是1就不能再减少了
this.shopmsg[a].num--;
}
},
del(a){//删除
this.shopmsg.splice(a, 1);
},
all(){//全选和取消全选(是通过改变json中的check的属性值达到全选的目的)
if($('.all')[0].checked == true){
this.shopmsg.forEach(function(val,index){
val.check = true;
})
}else{
this.shopmsg.forEach(function(val,index){
val.check = false;
})
}
}
},
computed:{
total(){//计算总价
var totalPrice = 0;
this.shopmsg.forEach(function(val,index){
if(val.check == true){//如果check属性值为true,表示选中,就计入总价
totalPrice = totalPrice+val.num * val.onePrice;
}
})
return '¥'+totalPrice;
}
}
})
这个小demo就到此结束了,在这个过程中,我遇到的卡点有以下几点:
1.想使用computed计算单个商品的总价,因为不了解数组对象的forEach方法,对this.shopmsg这个数组使用了for循环,结果return时只返回了一条数据。但这也是意料之中的,程序遇到return就结束了,所以只能计算一条数据。后来直接在插值表达式{{'¥'+v.onePrice*v.num}}里解决了这个问题。同时也了解了forEach这个方法。
2.没办法通过勾选框选中实现动态计算商品总价。原因:checkbox选中属性checked不会存到数据库;解决:通过改变在数据库的属性check的值,实现计算商品总价。因为只有数据改变,页面渲染的值才会改变。