vue Router 是vue.js的官方路由管理器,能夠經過hash匹配組件並渲染而不刷新頁面vue
hash模式瀏覽器
history模式bash
經過不一樣參數,來匹配到同一組件服務器
好比咱們有一個通用的文章詳情頁,須要經過不一樣的文章id來顯示不一樣的內容,則咱們能夠經過 article:id 來完成異步
$route.paramsthis
一個 key/value 對象,包含了動態片斷和全匹配片斷spa
article/:id 轉換爲> $route.params.idcode
article/123 => $route.params.id = 123component
$route.queryrouter
一個 key/value 對象,表示 URL 查詢參數
article?id='123' => $route.params.id = '123'
注意!改變路由的參數不會觸發進入/離開的導航守衛
全局前置守衛< beforeEach >
當導航被觸發時會被調用,守衛是異步解析執行的,當守衛未resolved以前,導航一直處於等待
=> code <=
router.beforeEach((to, from, next) => {
······
})
複製代碼
全局解析守衛< beforeResolve >
當導航被確認同時組件內守衛和異步守衛都解析後觸發
全局後置鉤子< afterEach >
導航跳轉完成後被觸發
router.afterEach((to, from) => {
······
})
複製代碼
beforeEnter
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
beforeEnter: (to, from, next) => {
// ...
}
}
]
})
複製代碼
僅限在組件內定義使用
beforeRouteEnter
beforeRouteEnter (to, from, next) {
// 不!能!獲取組件實例 `this`
// 由於當守衛執行前,組件實例還沒被建立
}
複製代碼
beforeRouteEnter (to, from, next) {
next(vm => {
經過vm訪問組件實例
})
}
複製代碼
beforeRouteUpdate
beforeRouteUpdate (to, from, next) {
// 能夠訪問this
this.name = to.params.name // 能夠獲取路由參數
next()
}
複製代碼
beforeRouteLeave
beforeRouteLeave (to, from, next) {
const answer = window.confirm('Do you really want to leave? you have unsaved changes!')
if (answer) {
next()
} else {
next(false) // 可經過此方法取消導航
}
}
複製代碼