关于实现思路在初次使用JS实现购物车时就有所讲解,其实实现思路都大致相同,理解了实现思路就很简单了,不明白的小伙伴可以翻看一下以前的相关文章。
购物车
{{ flag ? "编辑" : "取消" }}
{{ item.title }}
小米系列
¥{{ item.pprice }}
合计 {{totalPrice}} 元
删除
移入收藏
删除
// 引入vue
import Vue from 'vue';
// 引入vuex
import Vuex from 'vuex';
// 引入子模块
import cart from './cart.js';
// 使用vuex插件
Vue.use(Vuex);
// 创建 store 实例
const store = new Vuex.Store({
modules: {
cart,
}
})
// 暴露vuex
export default store;
export default {
//开启命名空间
namespaced: true,
state: {
list: [{
checked: false,
id: 11,
title: "商品标题111",
cover: "/static/images/demo/list/1.jpg",
// 选中商品属性
attrs: [{
title: "颜色",
selected: 0,
list: [{
name: '火焰红',
},
{
name: '炭黑',
},
{
name: '冰川兰',
}
]
},
{
title: "容量",
selected: 0,
list: [{
name: '64GB',
},
{
name: '128GB',
},
]
},
{
title: "套餐",
selected: 0,
list: [{
name: '标配',
},
{
name: '套餐一',
},
{
name: '套餐二',
}
]
},
],
pprice: 336,
num: 1,
minnum: 1,
maxnum: 10, // 该商品最大商品数,跟库存有关
},
{
checked: false,
id: 12,
title: "商品222",
cover: "/static/images/demo/list/1.jpg",
// 选中商品属性
attrs: [{
title: "颜色",
selected: 0,
list: [{
name: '火焰红',
},
{
name: '炭黑',
},
{
name: '冰川兰',
}
]
},
{
title: "容量",
selected: 0,
list: [{
name: '64GB',
},
{
name: '128GB',
},
]
},
{
title: "套餐",
selected: 0,
list: [{
name: '标配',
},
{
name: '套餐一',
},
{
name: '套餐二',
}
]
},
],
pprice: 200,
num: 1,
minnum: 1,
maxnum: 10, // 该商品最大商品数,跟库存有关
},
{
checked: false,
id: 13,
title: "商品标题333",
cover: "/static/images/demo/list/1.jpg",
// 选中商品属性
attrs: [{
title: "颜色",
selected: 0,
list: [{
name: '火焰红',
},
{
name: '炭黑',
},
{
name: '冰川兰',
}
]
},
{
title: "容量",
selected: 0,
list: [{
name: '64GB',
},
{
name: '128GB',
},
]
},
{
title: "套餐",
selected: 0,
list: [{
name: '标配',
},
{
name: '套餐一',
},
{
name: '套餐二',
}
]
},
],
pprice: 100,
num: 2,
minnum: 1,
maxnum: 10, // 该商品最大商品数,跟库存有关
}
],
// 设置一个数组用来承载商品列表中选中的那一条记录的id
selectId: [],
},
actions: {
// 全选
chooseAll(context) {
context.commit('CHOOSEALL')
},
// 单选
chooseItem(context, index) {
context.commit('CHOOSEITEM', index);
},
// 删除
delItem(context){
context.commit('DELITEM');
},
// 增加商品数量
changeNum(context,value){
context.commit('CHANGENUM',value)
}
},
mutations: {
// 全选
CHOOSEALL(state, value) {
if (state.list) {
state.list.forEach((item) => {
if (item.checked) {
item.checked = false;
} else {
item.checked = true;
}
})
}
},
// 切换每一条数据中的单选状态
CHOOSEITEM(state, index) {
let id = state.list[index].id;
let i = state.selectId.indexOf(id);
if (state.list) {
if (i != -1) {
state.selectId.splice(index, 1);
state.list[index].checked = false;
} else {
state.selectId.push(id);
state.list[index].checked = true;
}
}
},
// 删除每一条
DELITEM(state){
if(state.list){
state.list = [];
}
},
},
getters: {
// 比较选中数组中的长度是否与原数据数组长度相等
isChooseAll(state) {
return state.list.length == state.selectId.length;
},
// 计算总价
totalPrice(state){
let total = 0;
if(state.list){
state.list.forEach((item)=>{
if(item.checked){
total += item.pprice * item.num;
}
})
return total;
}
}
}
}