一、Vue-Router4官網
Vue-Router是Vue.js官方推出的一款用於構建SPA應用的路由庫,它已經成為Vue.js中一個非常重要的組成部分。Vue-Router4相對於前面的版本,不僅增加了一些新的特性,而且用法也有了一些變化。在Vue3中,Vue-Router已經成為了一個獨立的包,完全不再是Vue.js的一個插件。下面是Vue-Router4官網的地址。
import { createRouter, createWebHistory } from 'vue-router' const routes = [ { path: '/', name: 'Home', component: () => import('./views/Home.vue') }, { path: '/about', name: 'About', component: () => import('./views/About.vue') } ] const router = createRouter({ history: createWebHistory(process.env.BASE_URL), routes }) export default router
二、Vue-Router4過度抖動
在Vue3以前的版本中,我們可以採用vue-router的transition屬性進行頁面切換的過渡效果,但是在Vue-Router4.0中這個屬性已經廢棄,它被v-slot和transition組合的方式所代替。如果您之前使用了transition過渡, 在Vue-Router4.0版本下,您可以使用v-slot實現過渡效果。
三、Vue-Router4原理
Vue-Router4原理其實就是由兩個方面組成:路由器對象和路由器配置。其中路由器對象是由Vue-Router提供的,而路由器配置包括路由匹配規則、中間件、攔截器等信息。Vue-Router的處理原理是根據路由匹配規則,通過createMatcher函數,把路由表解析成一份映射表,然後通過Vue.mixin把beforeRouter和afterRouter鉤子函數注入到每個組件中。這樣在組件中運行時,就可以通過訪問$route來獲取路由信息,並根據$route.params來獲取路徑參數的值。
const matcher = createMatcher(routes) const beforeEachs = [] const afterEachs = [] Vue.mixin({ beforeCreate() { if (this.$options.router) { this._routerRoot = this this._router = this.$options.router this._router.init(this) Vue.util.defineReactive(this, '_route', this._router.history.current) } else { this._routerRoot = (this.$parent && this.$parent._routerRoot) || this } registerInstance(this, this._router) addBeforeHook({beforeEach: beforeEachs, afterEach: afterEachs}, this) }, destroyed() { unregisterInstance(this) removeBeforeHook({beforeEach: beforeEachs, afterEach: afterEachs}, this) } })
四、Vue-Router4傳參
在Vue-Router4中,我們可以使用props來對路由進行傳參。其中可以使用路由參數props: true來快速取出所有動態路由的參數並將其設置成組件的props,傳遞的參數將被合併入該組件的props中。此外,也可以使用props: {myProp: ‘myDefaultValue’}來傳遞默認值。
const router = new VueRouter({ routes: [ { path: '/user/:userId', name: 'user', component: User, props: true }, { path: '/blog/:blogId', name: 'blog', component: Blog, props: { myProp: 'defaultValue' } } ] })
五、Vue-Router4動態路由
Vue-Router4支持動態路由的創建,因此我們可以在運行時向路由表添加動態路由,在路由表中動態添加路由可以通過路由的addRoute方法,在路由表中動態刪除路由可以通過路由的removeRoute方法。
// 動態添加路由
const Blog = { template: 'blog原創文章,作者:MHTE,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/138527.html