time: 2019.6.5
update: 2020.3.16
author: heyunjiang
完整学习一遍之后,再来和介绍页的功能对比,看自己的掌握程度
<router-view>
作为全局组件,可以用在组件内部,用于匹配路由配置的 children
配置<router-view name="a">
,除了嵌套,也可以组合成兄弟元素。需要在配置中 component -> components<router-link>
总共就这2个全局组件采用先配置优先级最高匹配原则
const route = [{
path: '/user/:userId',
name: 'user',
component: User,
meta,
children
}]
routes: [
{ path: '/user/:id', component: User }
]
特点:
/user/12345678
,在组件内部使用 this.$route.param.id 访问beforeRouteUpdate
方法实现监听增加一个 name 参数,路由跳转、匹配时都可以使用 name
使用 props
字段传参,比如 { path: '/user/:id', component: User, props: {} }
,在路由组件内部使用 props 接收。
参数类型有:布尔、对象、函数
<router-link>
this.$router.push
,如果同时存在 path 和 params ,则 params 不生效router.replace(location)
redirect
字段alias
字段分为全局守卫、组件内守卫、路由独享的(在路由配置中实现)
next 方法
路由守卫只在路由组件内起效,在非路由组件上不起效
问题:
router.addRoute(parentName: string, route: RouteConfig)
这里指的是路由对应的组件懒加载,标准写法
const Foo = () => import('./Foo.vue')
const router = new VueRouter({
routes: [
{ path: '/foo', component: Foo }
]
})
实现原理:
静态路由:实现配置好,在应用初始化创建 router 对象时传入的配置,后续根据 url 变化渲染加载不同的组件,将组件内部的 <router-view>
与 路由配置的 children 匹配
动态路由:在 react 中,动态路由的概念是没有配置,route 本身作为一个组件,将 route 组件 prop 的 path
属性与浏览器 url 的 path 作匹配,成功才显示内容;路由嵌套也是在 route 加载的 component 组件内部再加载一个 route ;vue 还不知道。
总结区别
window.location['replace', 'assign]
来更新历史信息,history 采用 html5 的 pushState | replaceState
来直接实现vue-router 作为 vue 插件
export function install (Vue) {
const registerInstance = (vm, callVal) => {
let i = vm.$options._parentVnode
if (isDef(i) && isDef(i = i.data) && isDef(i = i.registerRouteInstance)) {
i(vm, callVal)
}
}
Vue.mixin({
beforeCreate () {
if (isDef(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)
},
destroyed () {
registerInstance(this)
}
})
Object.defineProperty(Vue.prototype, '$router', {
get () { return this._routerRoot._router }
})
Object.defineProperty(Vue.prototype, '$route', {
get () { return this._routerRoot._route }
})
Vue.component('RouterView', View)
Vue.component('RouterLink', Link)
}
源码解析