vue基础回顾 router

vue-router
1. 底层原理 hash 或者h5 histroy(有兼容性)
2. 使用的时候Vue需要引入VueRouter
Vue.use(VueRouter) //VueRouter 底层实际上是instal 安装了两个全局的组件 router-view 和router-link
默认路由:
 {
    path:'/',
    //component:Home //默认页
  //  redirect:'/home' 
    redirect:{name:'home'}  //也可以起一个名字
}
3. 路由跳转 
 <li><router-link :to="{path:'/home'}">首页</router-link></li>
 <li><router-link :to="{name:'home'}">首页</router-link></li> //name 会有兼容性问题

4. 一个路由想要加载多个组件
    ① 定义组件的时候采用路由的方式
    {
        name:'home',
        path:'/home',
    //  component:Home
        components:{
        default:Home,
        comp1:Comp1,
        comp2:Comp2
    }
    ② 引入组件Comp1 Comp2
    ③ 在组件显示的地方 添加 name属性
        <router-view name="comp1"></router-view>
        <router-view name="comp2"></router-view>
5. 二级路由
{
    path:'/user',
    component:User,
    children:[{
        path:'userAdd', //注意这里不要/,/代表根目录
        component:UserAdd
    },{
        path:'userList', //这里也可以这样写 /user/userList
        component:UserList
    }]
}

6. 路由钩子函数,不同的钩子之间会做什么
全局组件:
beforeEach(to,from,next):进入新的页面
beforeEnter 进入路由的配置当中
beforeRouteEnter(to,from,next) 单组件进入时
beforeRouteLeave(to,from,next) 单组件离开时
next(vm=>{}) 组件渲染完毕 会调用beforeRouteEnter钩子中 next中的回调函数
beforeResolve(to,from,next) 解析完成
afterEach(to,from,next) 当前进入完毕

7. 跳转页面 声明式跳转/编程式跳转
声明式跳转:<router-link :to="{path:'/home'}">首页</router-link>
编程式跳转 :this.$router.push("/user/userList"); 

8. 怎么取得路径的参数
路径传参
?id=1
{{this.$route.query.id}} 通过?路径参数
{{this.$route.params.id}} 通过路由

路由 path:'detail/:id'
<router-link to="user/detail/3">首页</router-link>

9.meta 路由校验用的
在 route.js中添加
 meta:{
        needLogin:true
    }
在路由钩子函数中通过to.matched去获取就能能到
let flag = to.matched.some(match=>match.meta && match.meta.needLogin === true)
可以校验
在路由钩子函数中to.matched 能狗获取到
4.路由懒加载
原文地址:https://www.cnblogs.com/moon-yyl/p/11884701.html