vue3 路由判断跳转到手机

vue yekong
import { createRouter, createWebHashHistory } from 'vue-router'
import Home from '../views/Home.vue'
import chargingRules from '../views/chargingRules.vue'
import userAgreement from '../views/userAgreement.vue'
import privacyPolicy from '../views/privacyPolicy.vue'
import h5 from '../views/h5.vue'
import user from '../views/user.vue'
import caseAdd from '../views/case/add.vue'
import caseDetail from '../views/case/detail.vue'
import caseEdit from '../views/case/edit.vue'
import About from '../views/About.vue'

function is_mobile () {
  var regex_match = /(nokia|iphone|android|motorola|^mot-|softbank|foma|docomo|kddi|up.browser|up.link|htc|dopod|blazer|netfront|helio|hosin|huawei|novarra|CoolPad|webos|techfaith|palmsource|blackberry|alcatel|amoi|ktouch|nexian|samsung|^sam-|s[cg]h|^lge|ericsson|philips|sagem|wellcom|bunjalloo|maui|symbian|smartphone|midp|wap|phone|windows ce|iemobile|^spice|^bird|^zte-|longcos|pantech|gionee|^sie-|portalmmm|jigs browser|hiptop|^benq|haier|^lct|operas*mobi|opera*mini|320x320|240x320|176x220)/i
  var u = navigator.userAgent
  if (null == u) {
    return true
  }
  var result = regex_match.exec(u)
  if (null == result) {
    return false
  } else {
    return true
  }
}

function QueryString (item) {
  var sValue = location.search.match(new RegExp('[\?\&]' + item + '=([^\&]*)(\&?)', 'i'))
  return sValue ? sValue[1] : sValue
}

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  }, {
    path: '/chargingRules',
    name: 'chargingRules',
    component: chargingRules
  }, {
    path: '/userAgreement',
    name: 'userAgreement',
    component: userAgreement
  }, {
    path: '/privacyPolicy',
    name: 'privacyPolicy',
    component: privacyPolicy
  }, {
    path: '/user',
    name: 'user',
    component: user,
    meta: {
      requiresAuth: true
    }
  }, {
    path: '/case/add',
    name: 'caseAdd',
    component: caseAdd,
    meta: {
      requiresAuth: true
    }
  }, {
    path: '/case/detail',
    name: 'caseDetail',
    component: caseDetail,
    meta: {
      requiresAuth: true
    }
  }, {
    path: '/case/edit',
    name: 'caseEdit',
    component: caseEdit,
    meta: {
      requiresAuth: true
    }
  }, {
    path: '/About',
    name: 'About',
    component: About,
    meta: {
      requiresAuth: false
    }
  }, {
    path: '/h5',
    name: 'h5',
    component: h5,
    meta: {
      requiresAuth: false,
      isH5: true
    }
  }
]
const router = createRouter({
  history: createWebHashHistory(),
  routes
})
router.afterEach(() => {
  document.body.scrollTop = 0
  document.documentElement.scrollTop = 0
})

router.beforeEach((to, from, next) => {
  if (is_mobile() && !to.meta.isH5) {
    next('/h5')
  } else {
    if (to.meta.requiresAuth) {
      if (!localStorage.getItem('userData')) {
        next('/')
      } else {
        next()
      }
    } else {
      next()
    }
  }
})
export default router

喜欢