vue
Automatic Routing
-
The traditional method of using routing
import Home from '@/pages/home' import My from '@/pages/my' ...... Add routes {path:'/home', name:' home', Component: home}, {path:'/my', name:' my', component: my},..... Access/home, / myCopy the code
-
Configure automatic route import without the need for each route import
-
Create a new js file ex: autoroute.js
-
Js code
let autoRoutes = [] let contexts = require.context('@/pages',true,/\.vue$/) contexts.keys().forEach(item => { // If (item.indexof ('components') == -1) {let name = item.replace('./','').replace('/index.vue','').replace('.vue','').replace(/\//g,'-') let path = item.replace('./','/').replace('/index.vue','').replace('.vue','') let src = item.replace('./','') autoRoutes.push({ path:path, name:name, component(resolve){ require([`@/pages/${src}`],resolve) } }) } }); export default autoRoutesCopy the code
-
Introduction/router/index. Js
import autoRoute from './autoRoute' export default new Router({ routes: [ ...autoRoute ] }) Copy the code
-
use
/home,/my,.... Copy the code
-