two pages: list and cart,list pages add shopping carts to vuex, use vue-router to jump to cart to modify the number of newly added items without updating the data, but the data in localStorage has been changed, you can modify the existing data, and refresh the page will be normal.
< H2 > mutations.js < / H2 >import Vue from "vue"
export default{
insert(state,goods){
if(typeof goods.num == "undefined"){
goods.num = 1;
}
Vue.set(state.cart,"p"+goods.id,goods);
},
delete(state,goods){
Vue.delete(state.cart,"p"+goods.id);
},
modify(state,data){
let num = data.num;
if(num>0){
Vue.set(state.cart["p"+data.goods.id],"num",num);
}
},
add(state,goods){
goods = state.cart["p"+goods.id];
let num = parseInt(goods.num) + 1;
if(num>0){
Vue.set(state.cart["p"+goods.id],"num",num);
}
},
reduce(state,goods){
goods = state.cart["p"+goods.id];
let num = parseInt(goods.num) - 1;
if(num>0){
Vue.set(state.cart["p"+goods.id],"num",num);
}
},
update(state){
localStorage.setItem("cart",JSON.stringify(state.cart));
}
}
< H2 > actions.js < / H2 >
import Vue from "vue"
export default{
insert({commit},goods){
commit("insert",goods);
commit("update");
},
delete({commit},goods){
commit("delete",goods);
commit("update");
},
add({commit},goods){
commit("add",goods);
commit("update");
},
reduce({commit},goods){
commit("reduce",goods);
commit("update");
},
modify({commit},data){
commit("modify",data);
commit("update");
},
update({commit}){
commit("update");
}
}
< H2 > goodsListItem.vue < / H2 >
<script>
import {mapGetters, mapActions, mapState} from "vuex"
export default{
props:["goods"],
computed:{
...mapGetters({
hasGoods: "cart/hasGoods"
})
},
methods:{
...mapActions({
insertCart: "cart/insert",
addCart: "cart/add"
}),
addCart(){
if(this.hasGoods(this.goods)){
this.addCart(this.goods);
}else{
this.insertCart(this.goods);
}
alert("!");
}
}
}
</script>
goodsCartItem.vue
<script>
import {mapActions} from "vuex"
export default{
props:["goods"],
data(){
return{}
},
methods:{
...mapActions({
add: "cart/add",
reduce: "cart/reduce",
modify: "cart/modify",
delete: "cart/delete"
}),
clickSelect(){
this.isSelected = !this.isSelected;
},
changeNum(dir){
if(dir == 1){
this.add(this.goods);
}else if(dir == -1){
this.reduce(this.goods);
}
},
setNum(){
let num = this.goods.num;
this.modify({goods:this.goods,num});
},
deleteCart(){
this.delete(this.goods);
}
}
}
</script>