路由 vue-router
静态路由
动态路由
路由跳转组件复用
watch:{
$router(to, from) {
to.params.路径参数名;
to.query.查询参数;
}
}
嵌套路由
{
path:'page', component:page, children:[
{path:'sub_page1', component:sub_page1},
{path:'sub_page2', component:sub_page2},
]
}
路由参数
/home/1/2/3
设置路由路径参数 {path:'/home', params:{a:1, b:2, c:3}}
获取路由路径参数 $route.params.x
/home/?a=1&b=2&c=3
设置路由查询参数 {path:'/home', query:{a:1, b:2, c:3}}
获取路由路径参数 $route.query.x
路由导航的两种方式
标签导航 <router-link :to="{name:'user', params:{userId:123}}">user</router-link>
编程式导航 router.push({name:'user', params:{userId:123}})
命名路由:通过name参数为路由起别名,直接通过别名访问路由页面。
{name:'user', params:{userId:123}}
{name:'user', query:{a:123}}
可以传递params和query
普通路由:
{path:'/user/:userId', params:{userId:123}}
只能传递query,不能传递params
$router.push()
跳转到指定url路径,并想history栈中添加一个记录,点击后退会返回到上一个页面
$router.replace()
跳转到指定url路径,但是history栈中不会有记录,点击返回会跳转到上上个页面 (就是直接替换了当前页面)
$router.go()
向前或者向后跳转n个页面,n可为正整数或负整数
路由守卫
全局钩子函数 beforeEach,afterEach
路由独享的钩子函数 beforeEnter 由于执行该钩子函数时还没有vue的实例所以该函数内不能使用this
组件内的钩子函数 beforeRouterEnter, beforeRouterUpdate, beforeRouterLeave
to,from,next
to:目标路由对象
from:来源路由对象
next() 放行
next(false) 阻止路由跳转
next('/login') 跳转到指定路由
next(error) 路由导航终止并且错误会被传递到router.onError()注册过的回调中
参考:https://www.cnblogs.com/dengyao-blogs/p/11576614.html