[TOC]

>[success] # router文件夹说明

接下来会讲一下 **正常路由结构** ,以及 **封装好的路由结构**。

>[success] ## 正常路由

**创建项目初始化路由** 会在 **src文件夹** 下生成一个 **router.js** 文件。

**router.js**

~~~

import Vue from 'vue'

import Router from 'vue-router'

import Home from './views/Home'

Vue.use(Router)

export default new Router({

routes: [

{

path: '/',

name: 'home',

component: Home

},

{

path: '/about',

name: 'about',

// route level code-splitting

// this generates a separate chunk (about.[hash].js) for this route

// which is lazy-loaded when the route is visited.

component: () => import(/* webpackChunkName: "about" */ './views/About.vue')

}

]

})

~~~

这种只是 **简单的路由(搭建项目初始化自动生成的路由文件)** ,如果以后 **复杂** 起来会**难已维护**。

>[success] ## 封装路由

1. 在 **src目录** 下创建一个 **router文件夹** ,这里的思想是把 **routes数组** 拆分成一个 **单独的js文件**,这样看着简洁也**方便维护**。

![](https://img.kancloud.cn/76/ee/76ee106ff5e570f4235eba358b6cbb6c_348x87.png)

2. **router文件夹**

**index.js**

~~~

import Vue from 'vue'

import Router from 'vue-router'

import routes from './router'

Vue.use(Router)

export default new Router({

routes // 这里使用ES6的简写写法,正常应该是这样写'routes : routes '

})

~~~

**router.js**

~~~

import Home from '@/views/Home'

export default [

{

path: '/',

name: 'home',

component: Home

},

{

path: '/about',

name: 'about',

// route level code-splitting

// this generates a separate chunk (about.[hash].js) for this route

// which is lazy-loaded when the route is visited.

component: () => import(/* webpackChunkName: "about" */ '@/views/About.vue')

}

]

~~~

Logo

前往低代码交流专区

更多推荐