Nuxt自定义路由

2021-08-10 10:11:47

每天早上读一篇美文,不管算鸡汤还是摆渡灵魂,看完后总是感触颇深,大多都是教我过好每一天,每一秒。留下成长的痕迹。言归正传,今天的成长来给你,也留给我!

虽然Nuxt可以自动生成路由配置,生成出来的路由配置可能并不满足我们的需求。所以,我们只能使用extendRoutes来自定义路由

下面是我的配置路由的方法:

首先新建router文件夹,并且新建文件defaultRouter.ts

// router/defaultRouter.js
import path from 'path'
const resolve = (pagePath) => path.resolve(process.cwd(), `./${pagePath}`)
export const $routes = [{
    path: '/index',
    name: 'Index',
    component: resolve('pages/index.vue')
  },
  //default皮肤
  {
    path: '/:siteid',
    name: 'index_default',
    meta: {
      skin: 'default'
    },
    component: resolve('pages/default/index.vue'),
  },
  {
    path: '/:siteid/:catname',
    name: 'list_default',
    meta: {
      skin: 'default'
    },
    component: resolve('pages/default/list.vue'),
  },
  {
    path: '/:siteid/:catname/:id',
    name: 'show_default',
    meta: {
      skin: 'default'
    },
    component: resolve('pages/default/show.vue'),
  },
  //id1皮肤
  {
    path: '/:siteid',
    name: 'index_id1',
    meta: {
      skin: 'id1'
    },
    component: resolve('pages/id1/index.vue'),
  },
  {
    path: '/:siteid/:catname',
    name: 'list_id1',
    meta: {
      skin: 'id1'
    },
    component: resolve('pages/id1/list.vue'),
  },
  {
    path: '/:siteid/:catname/:id',
    name: 'show_id1',
    meta: {
      skin: 'id1'
    },
    component: resolve('pages/id1/show.vue'),
  },
  //id2皮肤
  {
    path: '/:siteid',
    name: 'index_id2',
    meta: {
      skin: 'id2'
    },
    component: resolve('pages/id2/index.vue')
  },

]
const extendRoutes = (routes) => {
  routes.length = 0 // 清除 nuxt 自己生成的路由,这里不要用 空数组 赋值
  routes.push(...$routes)
}
export default { extendRoutes, middleware: ['whichSkin'] }

看了上面的配置,你肯定会奇怪,为什么我几个路径都一样,因为我们的需求就是要做不同的皮肤,我通过中间件whichSkin去判断路由使用哪个模板
贴出我的whichSkin.ts代码

import { frontTemplate } from '~/utils/tools/frontVisit'
export default function({ app, route, store, redirect }) {
  if (!route.params.siteid) return false
  frontTemplate(route.params.siteid).then(res => {

    if (route.fullPath == '/' + route.params.siteid) {
		//这里注意,router绑定在app上,并没有在route上
      app.router.push({
        name: `index_${res}`,
        params: { siteid: route.params.siteid }
      })
    }
  })
}

然后在nuxt.config.js配置文件中导入配置

import defaultRouter from './router/defaultRouter'
export default {
  // Global page headers: https://go.nuxtjs.dev/config-head
  head: {
		title: 'cmsfront',
		htmlAttrs: {
		  lang: 'en'
		},
	},
	...,
	router: defaultRouter,
}

关于

联系方式 :

mail: hey_cool@163.com ,
QQ:583459700

备案许可证编号:蜀ICP备16005545号-1 © COPYRIGHT 2015-2021 zhmzjl.com | by: KAPO