添加商品到购物车 Vuex

商品详情/购物车页面 code

<template>
	<div class="home">购物车车
		<button @click="addGood(1)">Add Good1</button>
		<button @click="addGood(2)">Add Good1</button>
		<button @click="addGood(3)">Add Good1</button>
		<ul>
			<li v-for="(item, index) in cartList"><input type="checkbox" v-model="item.selected" />{{item}} <button @click="sub(index)" :disabled="item.count <= 1">-</button>{{item.buyNumber}}<button @click="add(index)">+</button><button @click="deleteBook(index)">删除</button> </li>
		</ul>
		<p><input type="checkbox" :checked="isSelectAll" @click="selectAllClick" /> 全选</p>
		<p>共计:{{totalPrice}}  选中 {{checkedLength}}</p>
	</div>
</template>
<script type="text/javascript">
import { mapGetters, mapActions } from 'vuex'
export default {
	name: "Cart",
	data() {
		return {}
	},
	methods: {
		...mapActions(['addToCart']), //mapActions 辅助函数,直接用 vueX 中 Action 的函数
		addGood(id) {
			const good = {
				name: "商品" + id,
				id: id,
				desc: "商品" + id + "描述",
				price: id
			}
			this.addToCart(good);
		},
		add(index) { this.$store.commit('addGoodNum', index); },
		sub(index) { this.$store.commit('subGoodNum', index); },
		deleteBook(index) { this.$store.commit('removedGood', index); },
		selectAllClick() {
			if (this.isSelectAll) { //全选
				this.cartList.forEach(item => item.selected = false);
			} else { //全不选
				this.cartList.forEach(item => item.selected = true);
			}
		}
	},
	computed: {
		...mapGetters(['cartList', 'totalPrice']), //mapGetter 辅助函数
		checkedLength(){ //得到选中的商品的数量
			return this.cartList.filter(item => item.selected).length;
		},
		isSelectAll(){
			console.log("1");
			if(this.cartList.length == 0) return false;
			return !(this.cartList.filter(item => !item.selected).length);
		}
	},
	
}

</script>
<style scoped>
.home {
	height: 100vh;
	position: relative;
}

</style>

store/index.js code

import Vue from 'vue'
import Vuex from 'vuex'

//1.安装插件
Vue.use(Vuex)

//2.创建对象
const store = new Vuex.Store({
	state: { //这里放置全局变量
		cartList: [],
	},
	mutations: {
		addGoodToCartList(state, good) {
			good.selected = true; //添加商品的时候将购物车的选择状态设置为选中
				state.cartList.push(good);
		},
		addGoodNum(state, index) { //添加商品数量
			state.cartList[index].count++;
		},
		subGoodNum(state, index) { //减少商品数量
			state.cartList[index].count--;
		},
		removedGood(state, index) { //添加商品数量
			state.cartList.splice(index, 1);
		},
	},
	actions: {
		addToCart(content, good) { //逻辑都写在 action 中,让 mutation 只执行最简单的操作 
			//查找之前数组中是否有该商品
			let oldProduct = content.state.cartList.find(item => {
				return item.id == good.id;
			})
			//如果之前有该商品,则数量加1
			if (oldProduct) {
				oldProduct.count += 1;
			} else {
				good.count = 1;
				content.commit('addGoodToCartList', good);
			}
		}
	},
	getters: {
		cartList(state) {
			//得到列表,在使用的页面 引入 import {mapGetters} from 'vuex'	 
			//...mapGetters(['cartList']) 

			return state.cartList;
		},
		totalPrice(state) {
			//总价(用 good.selected 来判断下用户是否选中了该商品)
			//map: 相当于普通的遍历,会把函数的返回值赋给新数组 
			//reduce: 对数组中的所有内容进行汇总,这里的最后的 0 是给 preValue 一个初始化的值,这里执行的是一个递归的操作
			let total = state.cartList.map(good => good.selected ? good.price * good.count : 0).reduce((preValue, goodPrice) => preValue + goodPrice, 0);
			return '¥' + total.toFixed(2);
		}
	}
});
//3.导出 store  
export default store

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将商品添加购物车内,需要进行以下步骤: 1. 创建一个购物车组件,用于显示购物车中的商品信息和数量。 2. 创建一个商品列表组件,用于显示所有商品的列表。 3. 在商品列表组件中,为每个商品添加一个“添加购物车”按钮,并为该按钮绑定一个点击事件。 4. 在点击事件中,将该商品的信息添加购物车组件中的商品列表中,并更新购物车商品的数量和总价。 5. 可以使用 Vuex 来管理购物车的状态,包括购物车商品的数量和总价等信息。 以下是一个简单的代码示例: 1. 购物车组件 ``` <template> <div> <h3>购物车</h3> <ul> <li v-for="(item, index) in cartList" :key="index"> {{ item.name }} - {{ item.price }}元 x {{ item.quantity }} </li> </ul> <p>总价:{{ totalPrice }}元</p> </div> </template> <script> export default { computed: { cartList() { return this.$store.state.cartList; }, totalPrice() { return this.$store.getters.totalPrice; }, }, }; </script> ``` 2. 商品列表组件 ``` <template> <div> <h3>商品列表</h3> <ul> <li v-for="(item, index) in productList" :key="index"> {{ item.name }} - {{ item.price }}元 <button @click="addToCart(item)">添加购物车</button> </li> </ul> </div> </template> <script> export default { data() { return { productList: [ { id: 1, name: '商品1', price: 10 }, { id: 2, name: '商品2', price: 20 }, { id: 3, name: '商品3', price: 30 }, ], }; }, methods: { addToCart(item) { this.$store.commit('addToCart', item); }, }, }; </script> ``` 3. Vuex 状态管理 ``` import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); export default new Vuex.Store({ state: { cartList: [], }, getters: { totalPrice(state) { return state.cartList.reduce((total, item) => total + item.price * item.quantity, 0); }, }, mutations: { addToCart(state, item) { const existItem = state.cartList.find((i) => i.id === item.id); if (existItem) { existItem.quantity++; } else { state.cartList.push({ ...item, quantity: 1 }); } }, }, }); ``` 在上面的示例中,当用户点击“添加购物车”按钮时,将触发 addToCart 方法,该方法会将商品信息添加购物车列表中,并更新购物车商品的数量和总价。购物车组件会根据 Vuex 中的状态来显示购物车中的商品信息和总价。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值