vue中vuex的使用以及mapActions、mapMutations使用

news/2024/7/4 19:29:55

一、安装vuex

npm install vuex --save     // 如果安装了淘宝镜像,可以使用 cnpm安装

二、建目录

  • 关于module,它是对store的一个分割,将store分割成一个个小的模块,每个模块中又具有store完整的功能。他的使用主要面向一些状态非常多的大型应用
  • 在这里插入图片描述

这里建了入口index.js和modules目录,getters是为了方便获取状态,mutation-type为了管理方法

三、index.js中引入vuex

import Vue from 'vue';
import Vuex from 'vuex';
import getters from './getters'

Vue.use(Vuex);
const modulesFiles = require.context('./modules', true, /\.js$/)
// you do not need `import app from './modules/app'`
// it will auto require all vuex module from modules file
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
  // set './app.js' => 'app'
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
  const value = modulesFiles(modulePath)
  modules[moduleName] = value.default
  return modules
}, {})
const store = new Vuex.Store({
  modules,
  getters
})
export default store

四、user.js下分别建state、mutations、actions、getters

/**
 *  存放 用户 数据
 * **/
import FleetIdControllerApi from '@/api/FleetIdController';
import AuthorityGroupManage from '@/api/dataManages/AuthorityGroupManage';
import * as types from '../mutation-type'  // 引入定义的方法
// initial state
const state = {
  userInfo: {
    name: '调度员:小峰',
    scsFleetId: '',
    account: '',
    userId: '',
    license: [],
    roles: [71, 54],
  },
};

// getters
const getters = {
  userInfo(state) {
    return state.name;
  },
};

// actions
// 异步方法用actions
// actions不能直接修改全局变量,需要调用commit方法来触发mutation中的方法
const actions = {
  login(context, payload) {
    context.commit('login', payload);
  },
  logout(context) {
    context.commit('logout');
  },
  saveGlobalUserInfo(context, payload) {
    context.commit('saveGlobalUserInfo', payload);
  },
};
//解码
const decode = function(license) {
  if (typeof license === 'undefined') {
    license = 0;
  }
  let license_decoded = ('000000' + license.toString(2)).split('').reverse();
  var temp = [];
  let returnRules = (() => {
    var temp = [];
    license_decoded.forEach(function(value, index) {
      temp[index] = value === '1';
    });
    return temp;
  })();
  return returnRules;
};
//查询调度员权限信息
const queryUserLicense = function(id, fleetId, versionType) {
  AuthorityGroupManage.queryPossessLicense(
      {
        id: id,
        fleetId: fleetId,
        versionType: versionType,
      },
  ).then(res => {
    if (res.success) {
      var reslicense = res.obj;
      console.log('权限license权限license权限license权限license权限license');
      console.log(reslicense);
      state.userInfo.license = decode(reslicense);
    }
  }).catch(err => {
    // 异常情况
    console.log(err);
  });
};
// mutations
const mutations = {
  [types.SET_NUM](state, all) { //设置参数
    state.all = all;
  },
  login(state, payload) {
    // state.name = payload
    // localStorage.setItem(user_key, JSON.stringify(payload));
    //保存 用户登录时间
    let timespan = Date.parse(new Date());
    // localStorage.setItem(user_time, timespan);
  },
  logout(state) {
    state.userInfo = null;
    // localStorage.setItem(user_key, null);
  },
  [types.saveGlobalUserInfo](state, payload) {
    FleetIdControllerApi.getfleetId({
      userId: payload,
    }).then(res => {
      // 返回集团ID
      // this.scsFleetId = res.obj[0].fid;
      // this.user.userId = res.obj[0].user_id;
      state.userInfo.scsFleetId = res.obj[0].fid;
      state.userInfo.userId = res.obj[0].user_id;
      let license = res.obj[0].license;
      let scsFleetId = res.obj[0].fid;
      let userId = res.obj[0].user_id;
      state.userInfo.scsFleetId = res.obj[0].fid;
      state.userInfo.userId = res.obj[0].user_id;
      state.userInfo.licenseHigh = res.obj[0].licenseHigh;
      state.userInfo.licenseLow = res.obj[0].licenseLow;
      state.userInfo.managePriv = res.obj[0].managePriv;
      state.userInfo.userId = res.obj[0].user_id;
      state.userInfo.account = payload;
      // queryUserLicense(userId,scsFleetId,1)
      // queryUserLicense(93,scsFleetId,1)
      state.userInfo.license = decode(license);

    }).catch(err => {

    });
    // localStorage.setItem(user_key, null);
  },

};

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


五、main.js入口引入

在这里插入图片描述

六、调用

methods: {
      //vuex获取store中方法
      ...mapActions("user", ["login","logout"]),
      // ...mapActions({
      //   add: 'user/login' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
      // }),


      saveUserInfo(){
        //直接调用
        this.$store.dispatch("login","新名字");
        //通过mapActions获取方法调用
        console.log(this.login("casn"));
      },
      }

七、getters.js

const getters = {
  user: state => state.user,
  roles: state => state.user.userInfo.roles,
  license: state => state.user.userInfo.license,
  userInfo: state => state.user.userInfo,
}
export default getters

八、使用

console.log(this.$store.getters.user);
console.log("用户权限"+this.$store.getters.roles);
console.log(this.$store.getters.userInfo.license);

九、关于mapActions、mapMutations

  • mapActions 必须放在 methods中,因为 action 或者 mutation 都是方法.
  1. 文件中导入
import { mapActions ,mapMutations} from 'vuex';
      //vuex获取store中方法
      ...mapActions('user', ['login', 'logout']),
      ...mapActions({
        login: 'login', // 将 `this.login()` 映射为 `this.$store.dispatch('login')`
      }),
      ...mapMutations({
        login: 'login', // 将 `this.login()` 映射为 `this.$store.commit('login')`
      }),

      saveUserInfo() {
        //保存用户信息
        this.$store.dispatch('login', '新名字');
        this.login('casn');
      },

http://www.niftyadmin.cn/n/4204518.html

相关文章

vue聊天功能模块(十一)iview实现的右键下拉菜单

需求 点击会话列表某个会话&#xff0c;右击下拉菜单 自己懒得写&#xff0c;于是使用了组件 直接上代码思路是先让下拉菜单隐藏&#xff0c;右击显示&#xff0c;再通过iview源码&#xff0c;设置显示位置 <template><div><h1>jkfjjfkfkjk</h1><…

场景中材质球和贴图打印

在项目中&#xff0c;场景大小很重要&#xff0c;特别是场景多了以后&#xff0c;除了在场景上做动态的加载&#xff0c;还要及时卸载。 为了可以在更多的安卓手机上可以运行&#xff0c;就需要对于场景加以优化。 1.shader上&#xff0c;尽量使用程序员找的shader,不要找一些…

java函数前加个条件_java里为什么主函数前面要加static修饰 | 学步园

先说一下static1.static 修饰的域&#xff0c;我们叫静态域&#xff0c;它是归类所有的&#xff0c;被所有对象所共享&#xff0c;只有一个2.static修饰的区块&#xff0c;域只会初始化一次3.static修饰的域或方法&#xff0c;可以直接通过类的名字加上.进行调用4.static修饰的…

【雕爷学编程】Arduino动手做(138)---64位WS2812点阵屏模块3

37款传感器与执行器的提法&#xff0c;在网络上广泛流传&#xff0c;其实Arduino能够兼容的传感器模块肯定是不止这37种的。鉴于本人手头积累了一些传感器和执行器模块&#xff0c;依照实践出真知&#xff08;一定要动手做&#xff09;的理念&#xff0c;以学习和交流为目的&am…

js 数组插入删除

常用的方法是遍历数组&#xff0c;然后使用splice&#xff08;&#xff09;删除 这里我们使用es6 中findIndex&#xff08;&#xff09;查找&#xff0c;然后删除 function deleteFromArray(arr, compare) {const index arr.findIndex(compare)if (index > -1) {arr.spli…

在vue项目中 如何定义全局变量 全局函数

这里写自定义目录标题设置一个专用的的全局变量模块文件&#xff0c;模块里面定义一些变量初始状态&#xff0c;用export default 暴露出去&#xff0c;需要时导入即可一、变量二、方法设置一个专用的的全局变量模块文件&#xff0c;模块里面定义一些变量初始状态&#xff0c;用…

Unity定时器

需求是在项目中&#xff0c;会遇到很多倒计时功能&#xff0c;比如在线时间奖励&#xff0c;pve活动间隔5分钟 总结常见解决方法有三种 1.Update()每帧检查&#xff0c;适合用于界面上显示具体的数值&#xff0c;这是了准确性。在用户体验倒计时是最好的选择。 2.this.Invoke( …

编写高性能 Web 应用程序的10个技巧

常见的 ASP.NET 性能神话 有用的 ASP.NET 性能技巧和诀窍 在 ASP.NET 中处理数据库的一些建议 缓冲以及用 ASP.NET 进行后台处理 本文使用下列技术&#xff1a;ASP.NET&#xff0c;.NET 框架&#xff0c;IIS   用 ASP.NET 编写 Web 应用程序其轻松程度令人难以置信。它是…