在实际开发过程中,我们经常会有加入购物车的需求:
实现步骤:
在src下创建一个store文件夹
在store文件夹里建一个store.js文件
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
modules:{}
})
export default store
然后在main.js导入刚才建的store
import store from '@/store/store.js'
然后挂载到 Vue 的实例上。
然后创建一个购物车cart的store模块:cart.js
export default{
namespaced:true,//开启命名空间
state:()=>({
// 购物车的数组,用来存储购物车中每个商品的信息对象
// 每个商品的信息对象,都包含如下 6 个属性:
// { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
cart: [],
}),
mutations:{},
getters:{}
}
然后在 store/store.js
模块中,导入并挂载购物车的 vuex 模块
import Vue from 'vue'
import Vuex from 'vuex'
// 1. 导入购物车的 vuex 模块
import moduleCart from './cart.js'
Vue.use(Vuex)
const store = new Vuex.Store({
// TODO:挂载 store 模块
modules: {
// 2. 挂载购物车的 vuex 模块,模块内成员的访问路径被调整为 m_cart,例如:
// 购物车模块中 cart 数组的访问路径是 m_cart/cart
m_cart: moduleCart,
},
})
export default store
然后在商品详情页中使用 Store 中的数据
// 从 vuex 中按需导出 mapState 辅助方法
import { mapState } from 'vuex'
export default {
computed: {
// 调用 mapState 方法,把 m_cart 模块中的 cart 数组映射到当前页面中,作为计算属性来使用
// ...mapState('模块的名称', ['要映射的数据名称1', '要映射的数据名称2'])
...mapState('m_cart', ['cart']),
},
// 省略其它代码...
}
实现加入购物车的功能
在 store 目录下的 cart.js
模块中,封装一个将商品信息加入购物车的 mutations 方法,命名为 addToCart
。示例代码如下:
export default {
// 为当前模块开启命名空间
namespaced: true,
// 模块的 state 数据
state: () => ({
// 购