vue之起飞之旅

vuex modules使用redux的模式管理数据

2018-12-27  本文已影响0人  还好还好L

公司新项目为一套大的管理平台,3个大权限十几个小的权限的项目。框架选用vue和element-ui框架。考虑到权限级比较多所以使用了vuex的module管理项目。分开3个大模块来管理数据避免后期的管理出问题。
上代码

store/index.js

import Vue from 'vue'
import Vuex from 'vuex'
import 'babel-polyfill'
Vue.use(Vuex)

//导入3个模块
import provider from "./provider"
import company from "./company"
import community from "./community"

export default new Vuex.Store({
    modules:{
        provider,   
        community,
        company
    }
})

举例一个模块下面的文件夹

模块文件.jpg

看着这些用过redux的人一定感觉好熟悉。
我们来一个个举例这些文件

actions.js文件。指令中转站,这里面它执行的都不是自己的指令,而是我们在组件里面通过dispatch派发的指令,里面的函数第一个默认为context,可以当成store对像来看,这里结构出commit方法,commit是执行mutations的方法。

import * as types from './types'
import { instance, login, getUserInfo } from '@/api/provider'

export default {
  // 登录token开始
  toLogin ({ commit }, info) {
    return new Promise((resolve, reject) => {
      login(info).then(res => {
        if (res.status === 200) {
          commit(types.LOGIN, res.data.token)
          commit(types.LOGINSTATUS, true)
          instance.defaults.headers.common['Authorization'] = `Bearer ` + res.data.token
          window.sessionStorage.setItem('token', res.data.token)
          resolve(res)
        }
      }).catch((error) => {
        console.log(error)
        reject(error)
      })
    })
  },
  getUser ({ commit }) {
    return new Promise((resolve, reject) => {
      getUserInfo().then(res => {
        if (res.status === 200) {
          commit(types.USERINFO, res.data)
        }
      }).catch((error) => {
        reject(error)
      })
    })
  },
  logOut ({ commit }) {
    return new Promise((resolve, reject) => {
      commit(types.USERINFO, null)
      commit(types.LOGINSTATUS, false)
      commit(types.LOGIN, '')
      window.sessionStorage.removeItem('token')
    })
  }
  // 登录token结束

}

mutations.js文件,这个文件的函数,第一个参数为store里面的state对象(就是我们存数据的那个state啦)第二参数为,你想改变前一个参数的数据。这里相当于数据中转站。详情看vuex官方文档喽。

import * as types from './types.js'

export default {
  // 登录token
  [types.LOGIN]: (state, value) => {
    state.token = value
  },
  [types.USERINFO]: (state, info) => {
    state.userInfo = info
  },
  [types.LOGINSTATUS]: (state, bool) => {
    state.loginStatus = bool
  }
  // 登录token结束
}

state.js 这里就是存各种数据的地方

export default {
// 登录token
  token: window.sessionStorage.getItem('token'),
  userInfo: {},
  loginStatus: false,
  // 登录token结束
  num:0
}

然后就是每个地方的types.js 常量文件,用来避免我们变量名写错这种错误。

// 登录token
export const LOGIN = 'LOGIN'
export const TOKEN = 'TOKEN'
export const USERINFO = 'USERINFO'
export const LOGINSTATUS = 'LOGINSTATUS'
// 登录token结束

getters.js 文件我们这里暂时没有用到我就不写了,直接导出一个对象就行了
对象里面的函数接收的第一个参数就是你的state,然后再里面进行各种数据监听啦。

最后就是index.js文件 store/provider/index.js 这里把所有文件整合给外面的store管理,我这里没有使用别名,所以所有的名字都不要相同,变量名,方法名

import mutations from './mutations.js'
import actions from './actions.js'
import state from './state.js'
import getters from "./getters"
export default {
  state,
  mutations,
  actions,
  getters
}

然后大家都想知道怎么在项目里面使用??? 我这种写法的话getters,actions,mutations的方法依旧是正常的使用方法,就只有在组件里面的state取数据时需要带上模块名。不逼逼了上代码。


<template>
<el-button v-show="$store.getters.show" type="info">测试getters</el-button>
</template>
//actions
<script>
methods: {
   // 注册
   signup () {
           console.log("注册");
   //改变state
           console.log(this.$store.state.provider.num++);
   },
   // 登陆
   login (formName) {
           this.$refs[formName].validate((valid) => {
               if (valid) {
                   this.$store.dispatch('toLogin', {
                       loginUser: this.ruleForm.username,
                       loginPassword: this.ruleForm.password
                   }).then(() => {
                       this.$store.dispatch('getUser')

//代码太长不想写了。

</script>

至此拆分结束。

上一篇 下一篇

猜你喜欢

热点阅读