Vuex实现购物车功能(附:效果视频),供大家参考,具体内容如下
功能描述:
- 加购
- 删除
- 加减
- 全选反选
- 选中计算总价
- 存储
整体演示效果如下:
首先介绍一下Vuex:
Vuex 实例对象属性 主要有下面5个核心属性:
state : 全局访问的state对象,存放要设置的初始状态名及值(必须要有)
mutations : 里面可以存放改变 state 的初始值的方法 ( 同步操作–必须要有 )
getters: 实时监听state值的变化可对状态进行处理,返回一个新的状态,相当于store的计算属性(不是必须的)
actions : 里面可以存放用来异步触发 mutations 里面的方法的方法 ( 异步操作–不是必须的 )
modules : 存放模块化的数据(不是必须的)
一、主页面Home:
#app { .nav-top { width: 100%; position: fixed; top: 0; left: 0; z-index: 9; } .nav-bottom { margin-top: 50px; } }
二、购物车页面ShopCart:
全选 .goods-card { margin: 0; background-color: white; } .delete-button { height: 100%; } .car-box { width: 100%; margin-bottom: 5px; display: flex; flex-wrap: nowrap; align-items: center; .car-box-left { flex: 1; padding-left: 10px; } .car-box-right { flex: 12; } }
三、Vuex代码:
import Vue from 'vue'
import Vuex from 'vuex'
import VuexPersist from 'vuex-persist'
Vue.use(Vuex);
export default new Vuex.Store({
state: {
cartList: [], // 购物车数据
},
mutations: {
// 添加商品
add(state, item) {
// console.log(item)
let flag = false;
// 加购去重(通过id判断)
state.cartList.forEach(i => {
if (i.item.id == item.id) {
i.num++;
flag = true;
}
})
if (flag == false) {
state.cartList.push({
num: 1, // 添加数量默认为1
item, // 添加购物车商品数据
ckd: false, // 添加复选框初始化状态为false
})
}
// console.log(state.cartList)
},
// 删除商品
del(state, index) {
state.cartList.splice(index, 1)
// state.
},
// 改变数量------加减综合法 !!!
changeNum(state, index) {
state.cartList.num = index
},
// 全选全不选
ckd(state, newAll) {
state.cartList.forEach(item => {
item.ckd = newAll
})
}
},
// 计算 getters
getters: {
// 总价
total(state) {
let sum = 0;
state.cartList.forEach(item => {
// 如果复选框选中 计算总价
if (item.ckd == true) {
sum += item.item.actualPrice * item.num
}
})
return sum
}
},
actions: {},
modules: {},
// Vuex存储插件
plugins: [
new VuexPersist({
storage: window.localStorage,
}).plugin,
]
})
关于vue.js组件的教程,请大家点击专题vue.js组件学习教程进行学习。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



