用uniapp做电商项目时使用vuex实现数据的全局共享来做购物车页面
一.配置vuex:1.在项目根目录中创建store文件夹,专门用来存放vuex相关的模块2.在store目录中新建store.js文件3.在store.js初始化store的实例对象//1.导入Vue和Vueximport Vue from "vue";import Vuex from 'vuex';//2.将Vuex安装为Vue的插件Vue.use(Vuex);//3.创建store的实例对象c
·
一.配置vuex:
1.在项目根目录中创建store文件夹,专门用来存放vuex相关的模块
2.在store目录中新建store.js文件
3.在store.js初始化store的实例对象
//1.导入Vue和Vuex
import Vue from "vue";
import Vuex from 'vuex';
//2.将Vuex安装为Vue的插件
Vue.use(Vuex);
//3.创建store的实例对象
const store = new Vuex.Store({
//挂载store模块
modules:{},
})
//4.向外共享store的实例对象
export default store
4.在main.js中导入store实例对象并挂载到Vue的实例上:
import store from './store/stroe.js'
const app = new Vue({
...App,
//2.将store挂载到Vue实例上
store
})
二.创建购物车的store模块
1.在store目录当中新建cart.js文件
2.在cart.js当中初始化vuex模块
export default{
//为当前模块开启命名空间
namespaced:true,
//模块的state数据
state:()=>({
//购物车的数组,用来储存购物车中每个商品的信息对象
//每个商品的信息对象,都包含如下6个属性
//{ goods_id,goods_name,goods_price,goods_count,goods_small_logo,goods_state}
cart:[],
}),
//模块的mutations方法用来修改state当中的数据
mutations:{},
//模块的getters属性,相当于数据的包装器
getters:{}
}
3.在store.js中,导入并挂载购物车的vuex模块
//1.导入购物车的vuex模块
import moduleCart from './cart.js'
const store = new Vuex.Store({
//挂载store模块
modules:{
//挂载购物车的vuex模块,模块内成员的路径被调整为m_cart
//购物车模块中,cart数组的访问路径是m_cart/cart
m_cart:moduleCart,
}
})
三、在商品详情页中使用store当中的数据:
1.在jtsp.vue中的script结点下加入
//从vuex中按需导出mapState辅助方法
import {mapState} from 'vuex'
computed:{
//使用mapstate方法,把m_cart模块中的cart数组映射到当前页面中,作为计算属性使用
//...mapState('模块的名称',['要映射的数据名称'])
...mapState('m_cart',['cart']),
//无论是映射mutation方法、getters属性还是state当中的数据,都需要指定模块的名称
}
2.在页面渲染时,可以直接使用映射过来的数据:
四:实现加入购物车功能:
1.在store目录下的cart.js模块中,封装一个商品信息加入到购物车的mutations方法,命名为addToCart:
mutations:{
//把商品信息goods和cart模块中的state当中的信息进行比较
addToCart(state,goods){
//根据提交的商品的Id,查询购物车中是否存在这件商品
//如果不存在,则findResult为undefined
const findResult = state.cart.find((x) => x.goods_id === goods.goods_id);
if(!findResult){
//如果购物车中没有这件商品,则直接push
state.cart.push(goods);
}else{
//如果购物车中有这件商品,则直接让数量自增
findResult.goods_count++
}
}
},
2.在jtsp.vue下的script结点中,先把addTocart映射到当前页面,然后就可以通过this.addToCart得到数据
import {mapState,mapMutation} from 'vuex'
...mapMutatione('m_cart',['addToCart']),
buttonClick(e){
//1.判断是否点击了加入购物车按钮
if(e.content.text === '加入购物车'){
//2.组织一个商品的信息对象
const goods = {
goods_id:this.goods.id,
goods_name:this.goods.name,
goods_price:this.goods.price,
goods_count:1,
goods_small_logo:this.goods.logo,
goods_state:true,
}
}
//3.通过this调用映射过来的addToCart方法
this.addToCart(goods);
}
},
更多推荐
已为社区贡献8条内容
所有评论(0)