添加操作所需方法
操作按钮已经添加成功了,那就需要有对应的方法去执行,在 Vue.js 中,方法都定义在 methods 属性中。
减去数量
首先关注一下“减去数量”的定义:
methods: {
reduceQuantity: function (id) {
for (let i = 0; i < this.cartList.length; i++) {
if (this.cartList[i].id === id) {
this.cartList[i].count--;
break;
}
}
}
}
通过遍历找到目标记录,并将其 count 属性减一,如同 MVVM 的定义,当数据变更的时候,视图也跟随着变化。
但凡是存在于购物车内的商品,其数量至少应该为 1,为防止减到 0,不妨再加一个判断使其逻辑更为完美:
methods: {
reduceQuantity: function (id) {
for (let i = 0; i < this.cartList.length; i++) {
if (this.cartList[i].id === id) {
if (this.cartList[i].count > 1) {
this.cartList[i].count--;
}
break;
}
}
}
},
增加数量
methods: {
increaseQuantity: function (id) {
for (let i = 0; i < this.cartList.length; i++) {
if (this.cartList[i].id === id) {
this.cartList[i].count++;
break;
}
}
}
}
只需要针对 count 属性做 +1 操作即可。
删除
deleteItem: function (id) {
for (let i = 0; i < this.cartList.length; i++) {
if (this.cartList[i].id === id) {
// 询问是否删除
this.$Modal.confirm({
title: '提示',
content: '确定要删除吗?',
onOk: () => {
this.cartList.splice(i, 1);
},
onCancel: () => {
// 什么也不做
}
});
}
}
}
在删除逻辑中,当遍历到目标记录时,会询问用户是否真的要删除当前记录,这里用到了 $Modal 对话框,如果用户点击确定,那么就执行真正的删除,看一看效果:

非常漂亮考究的 iView Modal 对话框,令人赏心悦目,一见倾心。
至此,针对 Vue.js 和 iView 框架的体验就告一段落,后面抽时间再学习一下组件和 Render 函数,提升一下内功修养。
