Splitting routing files based on Vue+Webpack to realize management

  • 2021-09-20 19:26:13
  • OfStack

The fact is, if your project is not particularly large, there is no need to split it. If the project is large, it is necessary to consider splitting the route. Actually, this operation is not complicated.

When we use the vue-cli tool to create a new vue project, we have already created a new routing file src/router/index. js, which reads as follows:


import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'

Vue.use(Router)

export default new Router({
 routes: [
  {
   path: '/',
   name: 'HelloWorld',
   component: HelloWorld
  }
 ]
})

We use this document as a blueprint to make adjustments. For example, we now want to create a new route for news, and then there are 1 sub-routes under this route, so we can write this:

router/index. js file adjustment


// src/router/index.js
import Vue from 'vue'
import Router from 'vue-router'
//  Child route view VUE Component 
import frame from '@/frame/frame'

import HelloWorld from '@/components/HelloWorld'
//  Quote  news  Child route profile 
import news from './news.js'

Vue.use(Router)

export default new Router({
 routes: [
  {
   path: '/',
   name: 'HelloWorld',
   component: HelloWorld
  }, {
   path: '/news',
   component: frame,
   children: news
  }
 ]
})

As above, we can introduce vue component of 1 sub-route view, and then introduce news sub-route configuration file. Let's write these two files.

frame/frame Subroute View vue Component

< template >
< router-view / >
< /template >

The sub-routing view component is extremely simple. As above, three lines of code are enough. For the related contents of router-view, please see:

https://router.vuejs.org/zh/api/#router-view

router/news. js child route configuration file

In fact, configuring this file has nothing to do with vue, it is simply the export and import of js es 6.


import main from '@/page/news/main'
import details from '@/page/news/details'

export default [
 {path: '', component: main},
 {path: 'details', component: details}
]

As above, you can. We have completed the multi-file management of routing. In this way, is it very simple? If you have any questions, please leave a message in the comments, and I will take time to reply to you.

For more information, please refer to the official website: https://router.vuejs.org/zh/


Related articles: