vuex状态管理

一. state单一状态树

Vuex 使用单一状态树——是的,用一个对象就包含了全部的应用层级状态。至此它便作为一个“唯一数据源 (SSOT (opens new window))”而存在。

export default {
  userList: {},
  userlian: {},
  token: localStorage.getItem("token") || "",
};

二.mutation-types

export const RECEIVE_USER_LIST = "receive_user_list"; //接收用户基本信息
export const SET_TOKEN = "set_token"; //记录token
export const RECEIVE_USER_LIAN = "set_user_lian"; //记录手机联系人

三.mutations

更新state多个方法对象

import { RECEIVE_USER_LIST, RECEIVE_USER_LIAN } from "./mutation-types";
export default {
  // 用户基本信息
  [RECEIVE_USER_LIST](state, { userList }) {
    state.userList = userList;
  },
  // 联系人
  [RECEIVE_USER_LIAN](state, { userlian }) {
    state.userlian = userlian;
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
};

四.actions

通过mutation间接更新state多个方法对象

import { RECEIVE_USER_LIST, RECEIVE_USER_LIAN } from "./mutation-types";
import { reqinformation, reqTel } from "../api";
export default {
  // 同步记录用户基本信息
  recordList({ commit }, userList) {
    commit(RECEIVE_USER_LIST, { userList });
  },
  // 异步获取用户基本信息
  async getuserLists({ commit }) {
    // 发送异步ajax请求
    const result = await reqinformation();
    if (result.code1 === 0) {
      const userList = result.data;
      commit(RECEIVE_USER_LIST, { userList });
    }
  },
  // 同步记录手机联系人
  recorduserlian({ commit }, userlian) {
    commit(RECEIVE_USER_LIAN, { userlian });
  },
  // 异步获取手机联系人
  async getuserlian({ commit }) {
    // 发送异步ajax请求
    const result = await reqTel();
    if (result.code1 === 0) {
      const userlian = result.data;
      commit(RECEIVE_USER_LIAN, { userlian });
    }
  },
  setToken(context, token) {
    context.commit("SET_TOKEN", token);
  },
};

五.index.js

这里是自动生成的不需要改变

import Vue from "vue";
import Vuex from "vuex";
import state from "./state";
import mutations from "./mutations";
import actions from "./actions";

Vue.use(Vuex);

export default new Vuex.Store({
  state,
  mutations,
  actions,
  modules: {},
});

目录结构

vuex状态管理

传送门:vuex

上一篇:RDMA技术详解(二):RDMA Send Receive操作


下一篇:云短信免费网站分享