global.js 2.4 KB
/*
 * @Descripttion:
 * @version: 1.0.0
 * @Author: limin
 * @Date: 2021-06-22 20:10:29
 * @LastEditors: limin
 * @LastEditTime: 2021-07-06 12:39:29
 * @FilePath: \gh-hall\src\mixins\global.js
 */
import store from '@/store'
import api from '@/api'
export default {
  data() {
    return {}
  },
  computed: {
    isSubmit() {
      return store.state.app.isSubmit
    }
  },
  beforeRouteEnter(to, from, next) {
    console.log('=============')
    const {
      meta: { auth, employeeType }
    } = to
    setKeepAlives(to, from)
    if (store.state.app.user) {
      if (to.name == 'SalesCustomerDetail' && store.state.app.isDennied) {
        return next({ name: 'PermissionDennied' })
      }
      return next()
    }
    if (auth) {
      const code = qs('code')
      if (code) {
        store
          .dispatch('login', { code, type: employeeType })
          .then(res => {
            if (to.name == 'SalesCustomerDetail') {
              api.user
                .customerDetailPermission()
                .then(({ code, data }) => {
                  if (code == 200 && data == true) {
                    next()
                  } else {
                    throw new Error('PermissionDennied')
                  }
                })
                .catch(err => {
                  store.dispatch('setIsDennied', true)
                  next({ name: 'PermissionDennied' })
                })
              // .catch(err => next())
            } else {
              next()
            }
          })
          .catch(res => next(false))
      } else {
        next(false)
      }
    } else {
      next()
    }
  }
}
function setKeepAlives(to, from) {
  const isBack = to.meta.deepth < from.meta.deepth
  const tranName = `slide-${{ true: 'right', false: 'left' }[isBack]}`
  store.dispatch('setTransitionName', tranName)
  // 如果要to(进入)的页面是需要keepAlive缓存的,把name push进keepAlives中
  if (to.meta.keepAlive) {
    store.dispatch('pushKeep', to.name)
  }
  // 如果 要 form(离开) 的页面是 keepAlive缓存的,
  // 再根据 deepth 来判断是前进还是返回
  // 如果是返回删除之前的keepAlive缓存:
  if (from.meta.keepAlive && isBack) {
    store.dispatch('removeKeep', [from.name])
  }
}
function qs(name) {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
  var r = window.location.search.substr(1).match(reg)
  if (r != null) return unescape(r[2])
  return null
}