vue的cli中自定义router


1.安装router

npm install vue-router

 2.为了方便管理在components同级创建router文件夹

3.在文件夹中创建index.js文件,就是router文件

import Vue from 'vue'
import Router from 'vue-router'
import routes from './routes'
Vue.use(Router)
const router = new Router({
    routes
})
router.beforeEach((to,from,next)=>{
    if(to.matched.some((route)=>route.meta.Auth)){
        next({
            path:'/login',
            query:{
                returnURL:to.path
            }
        })
    }else{
         next()
    }
   
})
export default router

 4.在这里是把routes分离开,作为一个模块进行定义,在index.js中引入,这样可以使模块更加的细化

import Artical from '../views/Artical'
import Channel from '../views/Channel'
import Index from '../views/Index'
import Setting from '../views/Setting'
import Base from '../views/setting/Base'
import Password from '../views/setting/Password'
import Avatar from '../views/setting/Avatar'
import Login from '../views/Login'
const routes = [
    {
        path: '/',
        component: Index,
        redirect:'/artical/1',
        children: [
            {
                path: 'artical/:id',
                component: Artical
            },
            {
                path: 'channel/:id',
                component: Channel
            },
            {
                path:'setting',
                component:Setting,
                meta:{
                    Auth:true
                },
                redirect:'/setting/base',
                children:[
                    {
                        path:'base',
                        component:Base
                    },
                    {
                        path:'password',
                        component:Password
                    },
                    {
                        path:'avatar',
                        component:Avatar
                    }
                ]
            }

        ]
    },{
        path:'/login',
        component:Login
    }
]
export default routes

5.其他文件使用的时候,在routes.js中进行定义就可以啦