1.接口数据:food.json
[{
"id": 11,
"name": "鱼香肉丝",
"price": 12
}, {
"id": 22,
"name": "宫保鸡丁",
"price": 14
}, {
"id": 34,
"name": "土豆丝",
"price": 10
}, {
"id": 47,
"name": "米饭",
"price": 2
},{
"id": 49,
"name": "蚂蚁上树",
"price": 13
},
{
"id": 50,
"name": "腊肉炒蒜薹",
"price": 15
}]
2.store数据:index.js
import Vue from "vue";
import Vuex from 'vuex';
import axios from 'axios';
Vue.use(Vuex);
const state = {
shop_list:[],
add:[],
count:0
}
const getters ={
count(state){
return state.count;
},
//1-1.获取商品列表
// getShopList:state => state.shop_list,
getShopList(state){
return state.shop_list
},
//1-2.获取购物车列表
addShopList(state){
return state.add;
},
//1-3.获取总数量
totalNum:(state,getters) =>{
let total =0;
getters.addShopList.map(n=>{
total += n.num;
})
return total;
},
//1-4.计算总价格
totalPrice:(state,getters)=>{
let total=0;
getters.addShopList.map(n=>{
total += n.num*n.price
})
return total;
}
}
const actions={
add({commit},n){
commit('add',n);
},
//2-1.加入购物车
addToCart({commit},product){
commit('addCart',product)
},
//2-2.清空购物