vuex实现购物车的增加减少移除,从零开始学数据结构和算法

26 阅读3分钟

最后

今天的文章可谓是积蓄了我这几年来的应聘和面试经历总结出来的经验,干货满满呀!如果你能够一直坚持看到这儿,那么首先我还是十分佩服你的毅力的。不过光是看完而不去付出行动,或者直接进入你的收藏夹里吃灰,那么我写这篇文章就没多大意义了。所以看完之后,还是多多行动起来吧!

可以非常负责地说,如果你能够坚持把我上面列举的内容都一个不拉地看完并且全部消化为自己的知识的话,那么你就至少已经达到了中级开发工程师以上的水平,进入大厂技术这块是基本没有什么问题的了。

开源分享:docs.qq.com/doc/DSmRnRG…

mutations: {

// 加

addCar(state, params) {

let CarCon = state.carList;

// 判断如果购物车是否有这个商品,有就只增加数量,否则就添加一个

// some 只要有一个isHas为true,就为true

let isHas = CarCon.some((item) => {

if (params.id == item.id) {

item.num++;

return true;

} else {

return false;

}

})

if (!isHas) {

let obj = {

"id": params.id,

"title": params.title,

"price": params.price,

"num": 1,

}

this.state.carList.push(obj)

}

},

// 减

reducedCar(state,params){

let len=state.carList.length;

for(var i=0;i<len;i++){

if(state.carList[i].id==params.id){

state.carList[i].num--

if(state.carList[i].num==0){

state.carList.splice(i,1);

break;

}

}

}

},

//移出

deleteCar(state,params){

let len=state.carList.length;

for(var i=0;i<len;i++){

if(state.carList[i].id==params.id){

state.carList.splice(i,1);

break;

}

}

},

// 初始化购物车,有可能用户一登录直接进入购物车

// initCar(state, car) {

// state.carList = car

// },

},

actions: {

// 加

addCar({ commit }, params) {

// console.log(params) //点击添加传过来的参数

// 使用setTimeout模拟异步获取购物车的数据

setTimeout(function () {

let result = 'ok'

if (result == 'ok') {

// 提交给mutations

commit("addCar", params)

}

}, 100)

},

// 减

reducedCar({ commit }, params) {

// console.log(params) //点击添加传过来的参数

// 使用setTimeout模拟异步获取购物车的数据

setTimeout(function () {

let result = 'ok'

if (result == 'ok') {

// 提交给mutations

commit("reducedCar", params)

}

}, 100)

},

// 移出

deleteCar({ commit }, params) {

// console.log(params) //点击添加传过来的参数

// 使用setTimeout模拟异步获取购物车的数据

setTimeout(function () {

let result = 'ok'

if (result == 'ok') {

// 提交给mutations

commit("deleteCar", params)

}

}, 100)

}

// initCar({ commit }) {

// setTimeout(function () {

// let result = 'ok'

// if (result == 'ok') {

// // 提交给mutations

// commit("initCar", [{

// "id": 20193698,

// "title": '我是购物车原来的',

// "price": 30,

// "num": 100,

// }])

// }

// }, 100)

// }

},

getters: {

//返回购物车的总价

totalPrice(state) {

let Carlen = state.carList;

let money = 0;

if (Carlen.length != 0) {

Carlen.forEach((item) => {

money += item.price * item.num

})

return money;

} else {

return 0;

}

},

//返回购物车的总数

carCount(state) {

return state.carList.length

}

},

})

2. list.vue(商品列表)

#listBox { width: 900px; margin: 0 auto; }
  1. car.vue(购物车)