vuex 如何使用

vuex如何使用

以下实现一个通过vuex来存储购物车商品信息的小demo
"vue": "^3.2.13",
"vuex": "^4.0.2"

效果展示

vuex准备工作

1.下载vuex npm i vuex --save
2.在src下创建文件夹store
3.创建如下文件:

代码部分

index.js

引入所有vuex相关文件,vue3 和vue2有些不一样

    import Vuex from "vuex";
    import state from "./state";
    import mutations from "./mutations";
    import * as actions from "./actions";
    import * as getters from "./getters";
  
    export default new Vuex.Store({
      state,
      getters,
      actions,
      mutations,
    });

state.js

存放需要使用 vuex store的数据

    const state = {
      // 购物车列表
      shopList: [],
    };
    export default state;

mutations.js

修改state里面数据的唯一途径

    import * as types from "./mutation-types";

    const mutations = {
      // 添加到购物车
      [types.PUSH_TO_CART](state, product) {
        state.shopList.push({
          id: product.id,
          name: product.name,
          price: product.price,
          number: 1,
        });
      },
      // 添加数量
      [types.ADD_NUMBER](state, product) {
        const cartItem = state.shopList.find((item) => item.id === product.id);
        cartItem.number++;
      },
      // 移除购物车中的商品
      [types.REMOVE_PRODUCT](state, product) {
        state.shopList = state.shopList.filter((item) => item.id !== product.id);
      },
    };
    export default mutations;

mutation-types.js

存放mutations内方法的别名,便于统一管理

    // 添加到购物车
    export const PUSH_TO_CART = "PUSH_TO_CART";
    // 增加商品数量
    export const ADD_NUMBER = "ADD_NUMBER";
    // 移除购物车中的商品
    export const REMOVE_PRODUCT = "REMOVE_PRODUCT"

getters.js

state的计算属性,用于获取store内数据

    export const shopList = function (state) {
      return state.shopList;
    };

actions.js

用于操作mutations,可写一些简单的业务逻辑

    import * as types from "./mutation-types";

    /** 添加商品到购物车 */ 
    export const addProductToCart = function ({ commit, state }, product) {
      const cartItem = state.shopList.find((item) => item.id === product.id);
      if (cartItem) {
        commit(types.ADD_NUMBER, { id: product.id });
      } else {
        commit(types.PUSH_TO_CART, product);
      }
    };

main.js

    import { createApp } from 'vue'
    import App from './App.vue'
    import store from "./store/index"

    createApp(App).use(store).mount('#app')
posted @ 2022-08-03 17:22  Droll丶浅影  阅读(97)  评论(0)    收藏  举报