流浪のwolf

卷帝

导航

store文件夹的处理,vuex模块化modules

 

 index文件代码:

import Vue from "vue";
import Vuex from "vuex";
// 导入根getters
import getters from "./getters";
// 导入三个模块
import app from "./modules/app"; // 设置的更换
import settings from "./modules/settings"; // 配置的切换
import user from "./modules/user"; // 用户模块

Vue.use(Vuex);
// 实例化仓库
const store = new Vuex.Store({
  // 没有根state,mutation,action,全部都是采用模块化开发vuex
  // 注册模块
  modules: {
    app,
    settings,
    user,
  },
  // 根getters
  // getters: getters,
  getters,
});

export default store;

getters.js代码:

// 通过根getters建立对子模块state里面的数据的快捷访问
const getters = {
  sidebar: (state) => state.app.sidebar,
  device: (state) => state.app.device,
  token: (state) => state.user.token,
  username: (state) => state.user.userInfo.username,
  userId: (state) => state.user.userInfo.userId,
  staffPhoto: (state) => state.user.userInfo.staffPhoto,
  companyId: (state) => state.user.userInfo.companyId,
};
export default getters;

modules / user文件代码:

import { getToken, setToken, removeToken } from "@/utils/auth";
import { loginApi, getInfoApi, getUserInfoApi } from "@/api/user";
const state = {
  token: getToken(), // 读取cookie里面作为默认值
  userInfo: {}, //用户资料
};

const mutations = {
  // 设置token
  setToken(state, data) {
    state.token = data; // 存vuex
    setToken(data); // 存本地
  },
  // 移除token
  removeToken(state) {
    state.token = null;
    removeToken();
  },
  // 设置用户资料
  setUserInfo(state, data) {
    state.userInfo = data;
  },
  // 删除用户资料
  removeUserInfo(state) {
    state.userInfo = {};
  },
};

const actions = {
  // 登录操作
  async loginAction(context, data) {
    // 接收表单数据 data
    // 发生请求 loginApi,得到token
    let token = await loginApi(data);
    // 触发mutation,存储token
    context.commit("setToken", token);
  },
  // 获取用户资料的action
  async getUserProfileAction(context) {
    let res = await getInfoApi();
    let res2 = await getUserInfoApi(res.userId);
    context.commit("setUserInfo", { ...res, ...res2 });
  },
  // 退出操作
  quitAction(context) {
    context.commit("removeToken");
    context.commit("removeUserInfo");
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};

 

posted on 2022-11-05 07:47  流浪のwolf  阅读(158)  评论(0编辑  收藏  举报