1. 程式人生 > 實用技巧 >本專案中如何使用vuex

本專案中如何使用vuex

1、匯入 vuex 包並建立 store 物件

store/index.js中程式碼如下:通過modules引入app.js,user.js,permission.js.

import Vue from 'vue'
import Vuex from 'vuex'

import app from './modules/app'
import user from './modules/user'
import permission from './modules/permission'
import getters from './getters'

Vue.use(Vuex)

const store = new
Vuex.Store({ modules: { app, user, permission }, getters }) export default store

app.js中程式碼如下:

import Cookies from 'js-cookie'

const app = {
  state: {
    sidebar: {
      opened: !+Cookies.get('sidebarStatus'),
      withoutAnimation: false
    },
    device: 'desktop'
  },
  mutations: {
    TOGGLE_SIDEBAR: state 
=> { if (state.sidebar.opened) { Cookies.set('sidebarStatus', 1) } else { Cookies.set('sidebarStatus', 0) } state.sidebar.opened = !state.sidebar.opened state.sidebar.withoutAnimation = false }, CLOSE_SIDEBAR: (state, withoutAnimation) => { Cookies.
set('sidebarStatus', 1) state.sidebar.opened = false state.sidebar.withoutAnimation = withoutAnimation }, TOGGLE_DEVICE: (state, device) => { state.device = device } }, actions: { ToggleSideBar: ({ commit }) => { commit('TOGGLE_SIDEBAR') }, CloseSideBar({ commit }, { withoutAnimation }) { commit('CLOSE_SIDEBAR', withoutAnimation) }, ToggleDevice({ commit }, device) { commit('TOGGLE_DEVICE', device) } } } export default app

user.js中程式碼如下:

import { login, logout, getInfo, changeUser } from '@/api/login'
import {
  getToken,
  setToken,
  removeToken,
  setUserId,
  getUserId,
  setSuperType,
  getSuperType,
  removeSuperType,
  removeUserId,
  getEnterpriseId,
  setEnterpriseId,
  removeEnterpriseId,
  getEnterpriseType,
  setEnterpriseType,
  removeEnterpriseType,
  setUserTokenList,
  removeUserTokenList,
  getUserTokenList,
  getPtsUserInfo,
  setPtsUserInfo

} from '@/utils/auth'

const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    enterpriseId: getEnterpriseId(),
    enterpriseType: getEnterpriseType(),
    userId: getUserId(),
    superType: getSuperType(),
    roles: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ENTERPRISEID: (state, enterpriseId) => {
      state.enterpriseId = enterpriseId
    },
    SET_ENTERPRISETYPE: (state, enterpriseType) => {
      state.enterpriseType = enterpriseType
    },
    SET_SUPERTYPE: (state, superType) => {
      state.superType = superType
    },

    SET_USERID: (state, userId) => {
      state.userId = userId
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    }
  },

  actions: {// 登入
    ChangeUser({ commit }, params) {
      return new Promise((resolve, reject) => {
        changeUser(params).then(response => {
          if (response.success) {
            const data = response.data
            const dataObj = response.obj
            // 儲存使用者資訊到 ptsUserInfo
            const ptsUserInfo = {}
            ptsUserInfo.token = data.token
            ptsUserInfo.userId = data.userId
            ptsUserInfo.userName = data.userName
            ptsUserInfo.chinaName = data.chinaName
            ptsUserInfo.internalUser = data.internalUser
            ptsUserInfo.supper = data.supper
            ptsUserInfo.enterpriseId = data.enterpriseId
            ptsUserInfo.enterpriseName = data.enterpriseName
            ptsUserInfo.enterpriseType = data.enterpriseType
            ptsUserInfo.enterprises = data.enterprises
            ptsUserInfo.password = data.password
            setPtsUserInfo(ptsUserInfo)
            // 儲存使用者資訊到其他
            setToken(data.token)
            setEnterpriseId(data.enterpriseId)
            setUserId({ 'user': data.userId, 'chinaName': data.chinaName, 'userName': data.userName })
            setSuperType(data.supper)
            setUserTokenList(dataObj)
            setEnterpriseType(data.enterpriseType)
            commit('SET_TOKEN', data.token)
            commit('SET_ENTERPRISEID', data.enterpriseId)
            commit('SET_ENTERPRISETYPE', data.enterpriseType)
            commit('SET_SUPERTYPE', data.supper)
            commit('SET_USERID', data.userId)
            commit('SET_NAME', data.userName)
            resolve(response)
          } else {
            resolve(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 登入
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        login(username, userInfo.password, userInfo.type, userInfo.checkCode, userInfo.codeToken, userInfo.phone, userInfo.code).then(response => {
          if (response.success) {
            const data = response.data
            const dataObj = response.obj
            // 儲存使用者資訊到 ptsUserInfo
            const ptsUserInfo = {}
            ptsUserInfo.token = data.token
            ptsUserInfo.userId = data.userId
            ptsUserInfo.userName = data.userName
            ptsUserInfo.chinaName = data.chinaName
            ptsUserInfo.internalUser = data.internalUser
            ptsUserInfo.supper = data.supper
            ptsUserInfo.enterpriseId = data.enterpriseId
            ptsUserInfo.enterpriseName = data.enterpriseName
            ptsUserInfo.enterpriseType = data.enterpriseType
            ptsUserInfo.enterprises = data.enterprises
            ptsUserInfo.password = data.password
            setPtsUserInfo(ptsUserInfo)
            // 儲存使用者資訊到其他
            setToken(data.token)
            setEnterpriseId(data.enterpriseId)
            setUserId({ 'user': data.userId, 'chinaName': data.chinaName, 'userName': data.userName })
            setSuperType(data.supper)
            setUserTokenList(dataObj)
            setEnterpriseType(data.enterpriseType)
            commit('SET_TOKEN', data.token)
            commit('SET_ENTERPRISEID', data.enterpriseId)
            commit('SET_ENTERPRISETYPE', data.enterpriseType)
            commit('SET_SUPERTYPE', data.supper)
            commit('SET_USERID', data.userId)
            commit('SET_NAME', data.userName)
            resolve(response)
          } else {
            resolve(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 獲取選單
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo(state.token).then(response => {
          const data = response.data
          if (data && data.menus.length > 0) { // 驗證返回的roles是否是一個非空陣列
            commit('SET_ROLES', data.menus)
          } else {
            reject('沒有給該使用者新增許可權,請先新增許可權')
          }
          commit('SET_AVATAR', data.avatar)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ENTERPRISEID', '')
          commit('SET_ENTERPRISETYPE', '')
          commit('SET_SUPERTYPE', '')
          commit('SET_ROLES', [])
          commit('SET_USERID', '')
          removeToken()
          removeEnterpriseId()
          removeEnterpriseType()
          removeUserId()
          removeUserTokenList()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_ENTERPRISEID', '')
        commit('SET_ENTERPRISETYPE', '')
        commit('SET_SUPERTYPE', '')
        commit('SET_USERID', '')
        removeToken()
        removeEnterpriseId()
        removeEnterpriseType()
        removeSuperType()
        removeUserId()
        resolve()
      })
    }
  }
}

export default user

permission.js中程式碼如下:

import { asyncRouterMap, constantRouterMap } from '@/router'
/**
 * 通過meta.role判斷是否與當前使用者許可權匹配
 * @param roles
 * @param route
 */
function hasPermissionByMenus(menus, route) {
  if (route.meta && route.meta.code) {
    return menus.some(menus => menus.includes(route.meta.code))
  } else {
    return false
  }
}

/**
 * 遞迴過濾非同步路由表,返回符合使用者角色許可權的路由表
 * @param routes asyncRouterMap
 * @param roles
 */
function filterAsyncRouter(routes, menus, datas) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermissionByMenus(menus, tmp)) {
      const codeformenu = tmp.meta.code
      if (datas[codeformenu]) {
        tmp.name = datas[codeformenu].name
        tmp.meta.title = datas[codeformenu].name
        tmp.meta.icon = datas[codeformenu].icon
        if (tmp.children) {
          tmp.children = filterAsyncRouter(tmp.children, menus, datas)
        }
        res.push(tmp)
      }
    }
  })

  return res
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return new Promise(resolve => {
        const { menus } = data.menus.data
        const { datas } = data.menus.data
        const accessedRouters = filterAsyncRouter(asyncRouterMap, menus, datas)
        commit('SET_ROUTERS', accessedRouters)
        resolve()
      })
    }
  }
}

export default permission

getters.js程式碼如下:

const getters = {
  sidebar: state => state.app.sidebar,
  device: state => state.app.device,
  token: state => state.user.token,
  avatar: state => state.user.avatar,
  name: state => state.user.name,
  enterpriseId: state => state.user.enterpriseId,
  enterpriseType: state => state.user.enterpriseType,
  superType: state => state.user.superType,
  userId: state => state.user.userId,
  roles: state => state.user.roles,
  permission_routers: state => state.permission.routers,
  addRouters: state => state.permission.addRouters
}
export default getters

2、在main.js中引入store,並將 store 物件掛載到 vue 例項中

import store from './store'
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  render: h => h(App)
})

state在專案中的使用:

app.vue中程式碼如下:

<template>
  <div id="app">
    <router-view />
  </div>
</template>

<script>
export default {
  name: "app",
  created() {
    window.addEventListener("beforeunload", () => {
      localStorage.removeItem("store");
      localStorage.setItem("store", JSON.stringify(this.$store.state));
    });
  },
  destroyed() {
    localStorage.removeItem("store");
  }
};
</script>

Layout.vue中程式碼如下:

computed: {
    sidebar() {
      return this.$store.state.app.sidebar
    },
    device() {
      return this.$store.state.app.device
    },
    classObj() {
      return {
        hideSidebar: !this.sidebar.opened,
        openSidebar: this.sidebar.opened,
        withoutAnimation: this.sidebar.withoutAnimation,
        mobile: this.device === 'mobile'
      }
    }
  },

Actions在本專案中的使用:

handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          if (this.captchaShow) {
            this.confirmCode();
          }
          this.loading = true
          this.loginForm.checkCode = this.checkCode;
          this.loginForm.codeToken = this.codeToken;
          // this.loginForm.password = this.encryptedData(this.loginForm.password)
          const loginData = {
            checkCode: this.checkCode, // 圖片驗證碼
            codeToken: this.codeToken, // uuid
            username: this.loginForm.username,
            type: this.loginForm.type,
            password: this.encryptedData(this.loginForm.password),
            phone: this.phone,
            code: this.verifyCode // 簡訊驗證碼
          }
          this.$store.dispatch('Login', loginData).then((res) => {
            if (res.success) {
              this.$message.success('登陸成功')
              this.errorCount = 0
              this.$router.push({ path: this.redirect || '/' })
            } else {
              if (res.msg.indexOf('修改密碼') > 0) {
                this.resetShow = true
                this.resetMsg = res.msg
              } else if (res.msg.indexOf('鎖定') > 0) {
                this.$message.error(res.msg)
              } else if (res.msg.indexOf('簡訊驗證碼') > 0) {
                debugger
                this.$message.error(res.msg);
                this.phone = res.data;
                this.getVerifyCode();
                this.refreshCode();
                this.checkCode = ''
              } else {
                if (res.msg !== '' && res.msg != null) {
                  this.$message.error(res.msg)
                }
                this.errorCount = res.data.errorCount
              }
            }
          }).catch((error) => {
            console.log(error)
          }).finally(() => {
            this.loading = false
          })
        } else {
          return false
        }
      })
    },
methods: {
async logout() {
await this.$store.dispatch("app/logout");
this.$router.push("/login");
}
}
toggleSideBar() {
this.$store.dispatch('ToggleSideBar')
},
logout() {
this.$store.dispatch('LogOut').then(() => {
location.reload() // 為了重新例項化vue-router物件 避免bug
})
},
changeUser(token, userName, internalUser, enterpriseId) {
Cookies.set('Admin-Token', token)
this.$store.dispatch('ChangeUser', { userName: userName, internalUser: internalUser }).then(() => {
location.reload() // 為了重新例項化vue-router物件 避免bug
})
}
methods: {
handleClickOutside() {
this.$store.dispatch('CloseSideBar', { withoutAnimation: false })
}
}
methods: {
handleSetLanguage(lang) {
this.$i18n.locale = lang
this.$store.dispatch('setLanguage', lang)
this.$message({
message: 'Switch Language Success',
type: 'success'
})
}
}

getters在本專案中的使用:

getAllDeptAllUsers(){
console.log("進入了dept方法")
const modleCode = {'modleCode': this.nodeName + '資訊稽核',
'enterpriseId': this.$store.getters.enterpriseId};
deptJs.getAllDeptAllUsers(modleCode).then(res=>{
console.log(res);
console.log("進入了post");
this.departmentList = res.data;
console.log(this.deptUserList)
})
},
data () {
    return {
      enterpriseType: this.$store.getters.enterpriseType
    }
  },
 data() {
    return {
      listQuery: {
        page: 1,
        limit: 20,
        materialName: null,
        materialCode: null,
        enterpriseId:this.$store.getters.enterpriseId,
        materialType: 10
      }
    }
  },
computed: {
    language() {
      return this.languageTypeList[this.$store.getters.language]
    }
  },
computed: {
    errorLogs() {
      return this.$store.getters.errorLogs
    }
  }
accept: (file, done) => {
/* 七牛*/
// const token = this.$store.getters.token;
// getToken(token).then(response => {
// file.token = response.data.qiniu_token;
// file.key = response.data.qiniu_key;
// file.url = response.data.qiniu_url;
// done();
// })
done()
},
<script>
  import {mapGetters} from 'vuex'

  export default {
    components: {},
    computed: {
      ...mapGetters([
        'userId',
        'enterpriseId'
      ])
    },
    data() {
      return {
        listQuery: {
          page: 1,
          limit: 20,
          enterpriseId: null,
          varietyName: null
        }
      }
    },
    created() {
      this.listQuery.enterpriseId = this.enterpriseId
      this.getList()
    },