一個web應用路由定義的是否合理是判斷這個應用是否合格的基礎條件之一,在spa開發模式以前,前端開發基本不用考慮路由的定義這塊基本都是後臺在完成,但隨着spa的推廣先後端分離的大趨勢下,前端路由定義的任務便落在的咱們前端開發者身上。本節咱們就來聊聊vue中vue-router的路由定義與配置。html
import Foo from './Foo.vue'
import Test from './Test.vue'
複製代碼
const routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Test }
]
複製代碼
let router = new VueRouter({
routes,
//默認爲hash模式
mode:'history'
})
export default router
複製代碼
const router = new VueRouter({
routes // (縮寫) 至關於 routes: routes
})
const app = new Vue({
router
}).$mount('#app')
複製代碼
interface RouteConfig = {
path: string,//路徑
component?: Component,//路徑對應加載對組件
name?: string, // 命名路由
components?: { [name: string]: Component }, // 命名視圖組件
redirect?: string | Location | Function,//重訂向對路由
props?: boolean | Object | Function,
alias?: string | Array<string>,//別名
children?: Array<RouteConfig>, // 嵌套路由的自路由
beforeEnter?: (to: Route, from: Route, next: Function) => void,//路由守衛
meta?: any,//其餘項 掛載在this.$route上
// 2.6.0+
caseSensitive?: boolean, // 匹配規則是否大小寫敏感?(默認值:false)
pathToRegexpOptions?: Object // 編譯正則的選項
}
複製代碼
路由模式:改變視圖的同時不會向後端發出請求前端
mode:'history'//默認爲hash模式
複製代碼
經常使用api以下:vue
router.push
router.replace
router.go
router.back
router.forward
複製代碼
路由導航守衛 vue-router中經常使用到路由導航守衛有beforeEach和afterEachweb
const router = new VueRouter({ ... })
router.beforeEach((to, from, next) => {
// ...
next()
})
複製代碼
過渡動效:transition組件,使用方式以下vue-router
<transition>
<router-view></router-view>
</transition>
複製代碼
滾動:vue-router有個能夠控制路由跳轉到新頁面是的滾動位置的屬性後端
const router = new VueRouter({
routes: [...],
scrollBehavior (to, from, savedPosition) {
// return 指望滾動到哪一個的位置
}
})
複製代碼
注意: 這個功能只在支持 history.pushState 的瀏覽器中可用。詳細請查看官方文檔api
路由配置如今已是前端工程中必不可少的配置,合理的路由配置能大大提高用戶體驗度,而且還能改善項目結構。瀏覽器