Vue项目配置路由以及设置路由守卫的正确方式(无坑可食用)

一、首先安装路由插件

 cnpm install vue-router --save-dev

二、新建一个router文件夹,文件下新建一个index.js文件

 三、index.js中引入router,代码如下

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)
export const constantRoutes = [
  {
    path: '/PixiDemo',
    component: () => import('@/components/PixiExample/PixiDemo.vue'),
    hidden: true
  },
  {
    path: '/PixiRope',
    component: () => import('@/components/PixiExample/PixiRope.vue'),
    hidden: true
  },
  { path: '*', redirect: '/PixiDemo', hidden: true }
]
const createRouter = () =>
  new Router({
    // mode: 'history', // require service support
    scrollBehavior: () => ({ y: 0 }),
    routes: constantRoutes
  })

const router = createRouter()

// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}

export default router

scrollBehavior 是为了每次跳转路由页面都是在最顶部

四、在根目录下创建promission.js文件,里面配置路由守卫

import Axios from 'axios'
import router from './router'
router.beforeEach(async(to, from, next) => {
  Axios.get(url).then(res => {
    localStorage.setItem('syslogin', res.data)
  }).catch(error => {
    // window.location.href = 'http://www.baidu.com'
    this.$message({
      message: '用户信息不正确',
      type: 'warning'
    })
    console.log(error)
  })
  next()
})

router.afterEach(() => {
  // finish progress bar
  // NProgress.done()
})

五、main.js引入

import router from './router'

import '@/permission'

new Vue({

  router,

  render: h => h(App)

}).$mount('#app')

import Vue from 'vue'
import App from './App.vue'
import 'cesium/Widgets/widgets.css'
import 'leaflet/dist/leaflet.css'
import 'leaflet-velocity/dist/leaflet-velocity.css'
import * as echarts from 'echarts'
import router from './router'
import '@/permission'
Vue.config.productionTip = false
Vue.prototype.$echarts = echarts
new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值