Browse Source

代码优化

yuwenjun 3 năm trước cách đây
mục cha
commit
f5cd1c5d9d

+ 1 - 1
package.json

@@ -110,4 +110,4 @@
     "type": "git",
     "url": "git+https://github.com/PanJiaChen/vue-element-admin.git"
   }
-}
+}

+ 4 - 3
src/layout/components/Navbar.vue

@@ -38,7 +38,6 @@
 </template>
 
 <script>
-import { closeWebSocket } from '@/utils/WebSocketUtil'
 import { mapGetters } from 'vuex'
 import Breadcrumb from '@/components/Breadcrumb'
 import Hamburger from '@/components/Hamburger'
@@ -68,9 +67,11 @@ export default {
     },
     async logout() {
       this.$message.success('已退出当前账号')
-      this.$store.dispatch('user/logout')
-      closeWebSocket()
       setTimeout(() => {
+        // 退出登录重置用户信息
+        this.$store.dispatch('user/logout')
+        // 重置相关state
+        this.$store.dispatch('resetState')
         this.$router.replace('/login')
       }, 500)
     }

+ 8 - 14
src/permission.js

@@ -4,14 +4,11 @@ import { Message } from 'element-ui'
 import { getToken } from '@/utils/auth'
 import getPageTitle from '@/utils/get-page-title'
 
-const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist
+const whiteList = ['/login', '/auth-redirect']
 const toSupplier = ['/supplier/list', '/supplier']
 
-// const onlyPath = ['/auth/list', '/product/list', '/product/add', '/product/edit']
-
 router.beforeEach(async(to, from, next) => {
   // 设置页面名称
-  // eslint-disable-next-line indent
   document.title = getPageTitle(to.meta.title)
   // 获取token
   const hasToken = getToken()
@@ -25,7 +22,6 @@ router.beforeEach(async(to, from, next) => {
     if (toSupplier.includes(to.path) && store.getters.proxyInfo !== null) {
       store.dispatch('tagsView/delAllProxyView')
       store.commit('user/SET_PROXY_INFO', null)
-      console.log('关闭其他的标签')
     }
 
     if (to.path === '/login') {
@@ -34,7 +30,8 @@ router.beforeEach(async(to, from, next) => {
     } else {
       // 加载国家列表
       store.dispatch('app/setCountry')
-      const hasInitRouter = store.getters.initRouter // 是否需要初始化路由
+      // 是否需要初始化路由
+      const hasInitRouter = store.getters.initRouter
       if (hasInitRouter) {
         next()
       } else {
@@ -48,29 +45,26 @@ router.beforeEach(async(to, from, next) => {
           // 设置路由
           router.addRoutes(accessRoutes)
 
-          // 开启会话
+          // 初始化会话信息 条件:当前用户为管理员 && socket对象已创建成功
           if (!store.getters.socketState && store.getters.userIdentity === 1) {
             store.dispatch('webSocket/initMessage')
           }
 
-          // hack method to ensure that addRoutes is complete
-          // set the replace: true, so the navigation will not leave a history record
           next({ ...to, replace: true })
         } catch (error) {
-          // remove token and go to login page to re-login
-          await store.dispatch('user/resetToken')
+          store.dispatch('user/resetToken')
           Message.error(error || '未知错误,请重新登录')
           next(`/login?redirect=${to.path}`)
         }
       }
     }
   } else {
-    /* has no token*/
+    // token不存在并且访问的路由非拦截路由
     if (whiteList.indexOf(to.path) !== -1) {
-      // in the free login whitelist, go directly
+      // 允许访问
       next()
     } else {
-      // other pages that do not have permission to access are redirected to the login page.
+      // 跳转到登录页面
       Message({ message: '登录失效,请重新登录!', duration: 1500 })
       next(`/login`)
       return

+ 13 - 8
src/store/index.js

@@ -1,27 +1,32 @@
 import Vue from 'vue'
 import Vuex from 'vuex'
 import getters from './getters'
+import { closeWebSocket } from '@/utils/WebSocketUtil'
 
 Vue.use(Vuex)
 
-// https://webpack.js.org/guides/dependency-management/#requirecontext
+// 动态加载modules
 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 createStore = () => new Vuex.Store({
+// 创建store
+const store = new Vuex.Store({
   modules,
-  getters
+  getters,
+  actions: {
+    // 重置部分state
+    resetState({ commit }) {
+      commit('permission/RESET_STATE')
+      commit('tagsView/RESET_STATE')
+      closeWebSocket()
+    }
+  }
 })
 
-const store = createStore()
-
 export default store

+ 1 - 5
src/store/modules/app.js

@@ -8,8 +8,7 @@ const state = {
   },
   device: 'desktop',
   size: Cookies.get('size') || 'medium',
-  countryList: [],
-  isRefresh: true
+  countryList: []
 }
 
 const mutations = {
@@ -37,9 +36,6 @@ const mutations = {
   // 获取国家列表
   SET_COUNTRY: (state, list) => {
     state.countryList = list
-  },
-  SET_IS_REFRESH: (state, flag) => {
-    state.isRefresh = flag
   }
 }
 

+ 5 - 0
src/store/modules/permission.js

@@ -47,6 +47,11 @@ const mutations = {
   },
   SET_INITROUTER: (state, flag) => {
     state.initRouter = flag
+  },
+  RESET_STATE: (state) => {
+    state.routes = []
+    state.addRoutes = []
+    state.initRouter = false
   }
 }
 

+ 5 - 0
src/store/modules/tagsView.js

@@ -73,6 +73,11 @@ const mutations = {
         state.visitedViews.splice(i, 1)
       }
     }
+  },
+
+  RESET_STATE: (state) => {
+    state.visitedViews = []
+    state.cachedViews = []
   }
 }
 

+ 14 - 9
src/store/modules/user.js

@@ -53,12 +53,23 @@ const mutations = {
   },
   SET_SHOP_TYPE: (state, shopType) => {
     state.shopType = shopType
+  },
+  RESET_STATE: (state) => {
+    state.token = getToken()
+    state.name = userInfo?.name || ''
+    state.roles = formatRoles(userInfo?.userIdentity)
+    state.shopStatus = userInfo?.shopStatus || ''
+    state.authUserId = userInfo?.authUserId || ''
+    state.userIdentity = userInfo?.userIdentity || ''
+    state.proxyInfo = null
+    state.shopType = userInfo?.shopType || ''
+    state.brandId = userInfo?.brandId || ''
   }
 }
 
 const actions = {
   // 登录操作
-  login({ commit, action }, userInfo) {
+  login({ commit }, userInfo) {
     const { username, password } = userInfo
     return new Promise((resolve, reject) => {
       login({ mobileOrName: username.trim(), password: password })
@@ -69,7 +80,6 @@ const actions = {
           commit('SET_USERINFO', { shopStatus, authUserId, userIdentity, shopType, brandId }) // 保存用户信息
           commit('SET_ROLES', roles) // 根据用户类型生成角色列表
           commit('SET_NAME', name) // 保存用户名称
-          // commit('app/SET_IS_REFRESH', false)
           setToken(token) // cokies保存token
           setUser(response.data) // cokies保存当前用户信息
           console.log(response)
@@ -82,16 +92,11 @@ const actions = {
   },
 
   // 退出登录
-  logout({ commit, state, dispatch }) {
-    commit('SET_TOKEN', '') // 重置token
-    commit('SET_ROLES', []) // 重置角色权限表
-    commit('SET_PROXY_INFO', null)
-    commit('SET_NAME', '')
-
+  logout({ commit }) {
+    commit('RESET_STATE')
     removeToken() // 从cokies中移除token
     resetRouter() // 重置路由
     removeUser() // 从cokies中移除用户信息
-    dispatch('tagsView/delAllViews', null, { root: true }) // 关闭所有打开的标签页
   },
 
   // 移除token

+ 7 - 5
src/store/modules/webSocket.js

@@ -1,4 +1,4 @@
-import { closeWebSocket, createSoceket } from '@/utils/WebSocketUtil'
+import { createSoceket } from '@/utils/WebSocketUtil'
 import { getMessage } from '@/api/message'
 
 const state = {
@@ -6,21 +6,25 @@ const state = {
   socketState: false
 }
 const mutations = {
+  // 初始化socket
   INIT_SOCKET: (state, commit) => {
     createSoceket({ commit })
   },
+  // 更新消息 像消息队列中添加一条消息
   UPDATE_MESSAGE: (state, message) => {
     state.messageList.unshift(message)
   },
+  // 初始化消息列表
   INIT_MESSAGE: (state, list) => {
     state.messageList = list
     console.log(state.messageList)
   },
+  // 设置会话状态
   SET_SCOKET_STATE: (state, flag) => {
     state.socketState = flag
   },
+  // 修改消息状态
   SET_MESSAGE_STATE: (state, info) => {
-    console.log(info)
     if (info.type === 1) {
       state.messageList = state.messageList.map(v => {
         if (v.authId === info.id) {
@@ -39,6 +43,7 @@ const mutations = {
   }
 }
 const actions = {
+  // 初始化消息state
   initMessage({ commit }) {
     getMessage().then(res => {
       if (res.code !== 0) {
@@ -47,9 +52,6 @@ const actions = {
       commit('INIT_MESSAGE', res.data)
       commit('INIT_SOCKET', commit)
     })
-  },
-  colseSocket() {
-    closeWebSocket()
   }
 }
 

+ 0 - 8
src/views/login/index.vue

@@ -94,14 +94,6 @@ export default {
       immediate: true
     }
   },
-  created() {
-    // window.addEventListener('storage', this.afterQRScan)
-    const isRefresh = this.$store.getters.isRefresh
-    console.log(isRefresh)
-    if (!isRefresh) {
-      window.location.reload()
-    }
-  },
   mounted() {
     if (this.loginForm.username === '') {
       this.$refs.username.focus()

+ 4 - 1
src/views/password/index.vue

@@ -79,8 +79,11 @@ export default {
       })
     },
     async logout() {
-      await this.$store.dispatch('user/logout')
       setTimeout(() => {
+        // 退出登录重置用户信息
+        this.$store.dispatch('user/logout')
+        // 重置相关state
+        this.$store.dispatch('resetState')
         this.$router.replace('/login')
       }, 500)
     }