一、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/n/138527.html
微信扫一扫
支付宝扫一扫