第一步:用vue的脚手架创建项目
npm i vue-cli --g //如果已经全局安装过了,这步可以省去
第二步:初始化项目
npm init webpack 项目名称
第三步:安装vuex包
npm i vuex --save
第四步:新建store文件夹
接下来是代码部分,先看商品列表product.vue
<template>
<div class="product">
<h1>{{msg}}</h1>
<table>
<tr>
<th>id</th>
<th>名称</th>
<th>价格</th>
<th>操作</th>
</tr>
<tr v-for='item in shoplist' :key='item.id'>
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.price}}</td>
<td>
<div @click='addToCart(item)'>添加</div>
</td>
</tr>
</table>
</div>
</template>
<script>
import {mapGetters, mapActions} from 'vuex'
export default {
name:'product',
data(){
return{
msg:'vuex购物车'
}
},
computed:{
...mapGetters(['shoplist'])
},
methods:{
...mapActions(['addToCart'])
}
}
</script>
<style>
table{
width: 100%;
}
td{
width: 20%;
text-align: center;
}
h1{
text-align: center;
line-height:40px;
font-size:32px;
margin:20px 0;
}
.go{
width: 100px;
line-height: 40px;
text-align: center;
background-color: yellowgreen;
}
</style>
// 初始化数据,里面是商品列表
const state={
//商品列表
shoplist:[
{id:1,name:'韭菜鸡蛋',price:10.00},
{id:2,name:'水煮鱼片',price:30.00},
{id:3,name:'青椒肉丝',price:15.00}
],
}
// 向外输出数据的方法
const getters={
// 购物车列表
shoplist:state=>state.shoplist,
}
// 导出
export default {
state,
getters,
actions,
mutations
}
<tr v-for='item in shoplist' :key='item.id'>
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.price}}</td>
<td>
<div @click='addToCart(item)'>添加</div>
</td>
</tr>
<template>
<div class="list">
<h1>{{msg}}</h1>
<table>
<tr>
<th>id</th>
<th>名称</th>
<th>价格</th>
<th>数量</th>
<th>操作</th>
</tr>
<tr v-for='item in cartProduct' :key='item.id'>
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.price}}</td>
<td>{{item.num}}</td>
<td>
<div @click='addDetele(item)'>删除</div>
</td>
</tr>
</table>
</div>
</template>
<script>
import {mapGetters, mapActions} from 'vuex'
export default {
name:'product',
data(){
return{
msg:'已添加的商品'
}
},
computed:{
// 添加购物车
...mapGetters(['cartProduct'])
},
methods:{
// 删除事件
...mapActions(['addDetele'])
}
}
</script>
<style>
table{
width: 100%;
}
td{
width: 20%;
text-align: center;
}
h1{
text-align: center;
line-height:40px;
font-size:32px;
margin:20px 0;
}
</style>
给product上的添加按钮注册点击事件,运用vuex中的action方法,给addToCart事件实行异步数据操作
//新建一个空数组用来接收添加的数据
// 初始化数据,里面是商品列表
const state={
// 添加购物车数据存储
added:[]
}
// 异步数据操作
const actions={
// 添加到购物车
addToCart({commit},n){
//触发add事件
commit('add',{
id:n.id
})
}
}
//通过mutations方法,对数据做出改变
const mutations={
// 添加到购物车
add(state,{id}){
// console.log(state,{id})
//遍历added数组,find方法找出点击的id和added中的id是相等的情况下,这项数据让变量items接收
let items=state.added.find(n=>n.id==id)
//如果么有找到这项数据items,那么就添加到added数组中
if(!items){
state.added.push({id,num:1})
}else{
//如果added数组中已经存在添加的数据了,那么就让数量加加
items.num++
}
},
}
// 向外输出数据的方法
const getters={
// 添加购物车计算属性
cartProduct:state=>{
return state.added.map(({id,num})=>{
let _n=state.shoplist.find(n=>n.id===id)
return {
..._n,//es6方法,对象的集合
num
}
})
},
}
** 以此方法类推删除与总和与总量 **