map()
- map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
- map() 方法按照原始数组元素顺序依次处理元素。
- 注意: map() 不会对空数组进行检测。
- 注意: map() 不会改变原始数组。
this.$set()
受 ES5 的限制,Vue.js 不能检测到对象属性的添加或删除。因为 Vue.js 在初始化实例时将属性转为 getter/setter,所以属性必须在 data 对象上才能让 Vue.js 转换它,才能让它是响应的。要处理这种情况,我们可以使用$set()方法,既可以新增属性,又可以触发视图更新。
这两者可以配合使用,在购物车中实现是否选中功能。
HTML代码:
//购物车列表选中
<checkbox v-bind:checked="item.isSelect" @click="item.isSelect=!item.isSelect"></checkbox>
//底部全选
<checkbox-group>
<checkbox @click="selectProduct(isSelectAll)" v-bind:checked="isSelectAll" />全选
</checkbox-group>
JS代码:
//赋值给数组
方法名() {
var _this = this
axios.get('接口地址', {参数}).then(function (res) {
_this.list = res.data
/*赋值,是否选中*/
_this.list.map(function (item) {
_this.$set(item, 'isSelect', true);
})
}).catch(function (err) {
console.log(err)
})
},
selectProduct(_isSelect) {
//遍历List,全部取反
for (var i = 0, len = this.list.length; i < len; i++) {
this.list[i].isSelect = !_isSelect;
}
},
vue中computed函数:
isSelectAll() {
//如果List中每一条数据的isSelect都为true,返回true,否则返回false;
return this.list.every(
function (val) {
return val.isSelect
});
},
这样就实现了购物车的商品选中功能。