欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

简单的路由配置

程序员文章站 2024-02-12 12:48:16
...

将所有额度路由放在另一个文件中

export const myRouter = [
	{	//跳转路由总页面
		path: '/',	
		redirect: '/walletEntrance/home'
	},
	{	//404页面配置
    	path: '*',
   		component: () => import('../components/404.vue'),
	},
	{
		path: '/pay',
		name: 'pay',
		meta: {
			title: '支付',
			keepAlive: false,
		},
		component: () => import('../views/pay/index.vue'),
		children: [
			{
				path: 'home',
				name: 'home',
				meta: {
					title: '支付',
					keepAlive: false,
				},
				component: () => import('../views/pay/home.vue')
			}
		]
	}
]

在router文件夹中的index.js文件中

import Vue from 'vue'
import VueRouter from 'vue-router'
import { myRouter } from './routerTree'	//配置的路由

Vue.use(VueRouter)

const routes = myRouter

const router = new VueRouter({
  routes
})

export default router

index.js文件中也可以设置一些路由内的功能

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

Vue.use(Router)

export function asyncRouter(arr) {
  return arr.map(v => {
    let obj = {}
    for (let i in v) {
      obj[i] = v[i]
    }
    if (obj.component.includes('Layout')) {
      obj.component = () => import(/* webpackChunkName: "layout" */ '@/layout')
    } else {
      obj.component = resolve => require([`@/views/${v.component}`], resolve)
    }
    if (obj.children) {
      obj.children = asyncRouter(v.children)
    }
    return obj
  })
}

export function constantRoutes(arr = []) {
  return [
    {
      path: '/login',
      component: () => import(/* webpackChunkName: "login" */ '@/views/login/index'),
      hidden: true
    },
    {
      path: '/404',
      component: () => import(/* webpackChunkName: "404" */ '@/views/404'),
      hidden: true
    },
    {
      path: '/',
      component: () => import(/* webpackChunkName: "layout" */ '@/layout'),
      redirect: '/dashboard',
      children: [{
        path: 'dashboard',
        name: '工作台',
        component: () => import(/* webpackChunkName: "dashboard" */ '@/views/dashboard/index'),
        meta: { title: '工作台' }
      }]
    },

    ...arr,

    { path: '*', redirect: '/404', hidden: true }
  ]
}

let localRouter = localStorage.routerTree ? asyncRouter(JSON.parse(localStorage.routerTree)) : []

const createRouter = () => new Router({
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRoutes(localRouter)
})

export const router = createRouter()

export function resetRouter() {
  const newRouter = new Router()
  router.matcher = newRouter.matcher
}

export default router