Vue-笔记 Vuex的使用

VueX 是一个专门为 Vue.js 应用设计的状态管理构架,统一管理和维护各个vue组件的可变化状态(你可以理解成 vue 组件里的某些 data )

Vuex有五个核心概念:

  

       state, getters, mutations, actions, modules

  1. statevuex的基本数据,用来存储变量

  2. getters:从基本数据(state)派生的数据,相当于state的计算属性

  3. mutation:提交更新数据的方法,必须是同步的(如果需要异步使用action)。每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)

   回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数,提交载荷作为第二个参数。

     4. action:和mutation的功能大致相同,不同之处在于 ==》1. Action 提交的是 mutation,而不是直接变更状态。 2. Action 可以包含任意异步操作。

  5. modules:模块化vuex,可以让每一个模块拥有自己的statemutationactiongetters,使得结构非常清晰,方便管理。

见示例代码(modules,模块化Vuex,每一个模块拥有自己的statemutationaction,然后所有模块共用一个getters):

modules:看一下user.js代码:

state中用于存储变量,action中用于获取变量,并为变量赋值,并提交到mutationsmutations用于应用commit的变量

import { loginAPI, getUserInfoAPI } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { constantRouterMap, routerComponentMap} from '@/router'


const user = {
  state: {
    user: '',
    status: '',
    code: '',
    token: getToken(),
    name: '',
    avatar: '',
    introduction: '',
    roles: [],
    setting: {
      articlePlatform: []
    },
    routers: constantRouterMap,
    addRouters: [],
    buttons:[]
  },

  mutations: {
    SET_CODE: (state, code) => {
      state.code = code
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction
    },
    SET_SETTING: (state, setting) => {
      state.setting = setting
    },
    SET_STATUS: (state, status) => {
      state.status = status
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    },
    SET_BUTTONS: (state, buttons) => {
      state.buttons = buttons
    }
  },

  actions: {
    // 用户名登录
    LoginByUsername({ commit }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        loginAPI(username, userInfo.password).then(response => {
          commit('SET_TOKEN', 'JWT '+ response.result.token)
          setToken('JWT '+response.result.token)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetUserInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getUserInfoAPI(state.token).then(response => {
          if (!response.result) {
            reject('error')
          }
          commit('SET_NAME', response.result.username)
          localStorage.setItem("username", response.result.username);
          if (response.result.group && response.result.group.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES', response.result.group);
            let dataList = response.result.asyncRouterMap;
            dataList.forEach(menuItems => {
              menuItems.component = routerComponentMap[menuItems.component];
              // console.log(menuItems.component,11111);
              menuItems.children.forEach(item => {
                item.component =  routerComponentMap[item.component];
              });
            });
            // console.log(dataList,2222);
            commit('SET_ROUTERS',dataList)
            commit('SET_BUTTONS',response.result.buttons)
          } else {
            reject('getInfo: roles must be a non-null array !')
          }
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_NAME', '')
        commit('SET_ROUTERS', [])
        commit('SET_BUTTONS', [])
        removeToken()
        window.localStorage.removeItem('stage')
        resolve()
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_NAME', '')
        commit('SET_ROUTERS', [])
        commit('SET_BUTTONS', [])
        removeToken()
        window.localStorage.removeItem('stage')
        resolve()
      })
    }
  }
};


export default user

共有getters代码:

const getters = {
  sidebar: state => state.app.sidebar,
  language: state => state.app.language,
  device: state => state.app.device,
  visitedViews: state => state.tagsView.visitedViews,
  cachedViews: state => state.tagsView.cachedViews,
  token: state => state.user.token,
  avatar: state => state.user.avatar,
  name: state => state.user.name,
  introduction: state => state.user.introduction,
  status: state => state.user.status,
  roles: state => state.user.roles,
  setting: state => state.user.setting,
  // permission_routers: state => state.permission.routers,
  // addRouters: state => state.permission.addRouters,
  permission_routers: state => state.user.routers,
  addRouters: state => state.user.addRouters,
  buttons: state => state.user.buttons,
  errorLogs: state => state.errorLog.logs
}
export default getters

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值