一没酣、$router
$router
是一個全局路由對象垄懂,是new Router
的實例厘擂,先上console...
從console的結(jié)果看起來,在頁面上拿到的$router
對象正是new VueRouter
所創(chuàng)建router
對象匣吊。
進一步往里看,路由類上的一些方法就是眼熟的beforeEach
寸潦、push
色鸳、replace
、go
见转、back
等, 因此在其他組件直接調(diào)用如this.$router.replace()
方法就是調(diào)用router對象的方法命雀。
常用:
this.$router.push('/user') //跳轉(zhuǎn)路由
this.$router.replace('/user') //跳轉(zhuǎn)路由,但是不會有記錄斩箫,不入棧
相關源碼:
Vue.mixin({
beforeCreate () {
if (isDef(this.$options.router)) {
this._routerRoot = this // this指向vue實例
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)
},
// ...
})
// this.$options就是創(chuàng)建vue實例時傳入的{el:#app,router,render:h => h(App)}
// 當傳入router吏砂,將this._routerRoot指向vue實例,將傳入的router賦值給this._router
// 就相當于 this._routerRoot._router = this.$options.router校焦,即把options傳入的router賦給 this._routerRoot._router
Object.defineProperty(Vue.prototype, '$router', {
get () { return this._routerRoot._router }
})
// 給Vue.prototype對象添加$router屬性赊抖,添加屬性為 this._routerRoot._router
因此,Vue.prototype.$router
和options中傳入的router
等同, 則this.$router
就等同于new Router
的實例寨典。
二氛雪、$route
$route
是一個局部對象,表示當前正在跳轉(zhuǎn)的路由對象耸成,換句話說报亩,當前哪個路由處于活躍狀態(tài),$route
就對應那個路由井氢。還是先上console弦追,直觀感受一下。
常用:
$route.path
字符串花竞,等于當前路由對象的路徑劲件,如“/home/news”。
$route.params
對象,包含路由中的動態(tài)片段和全匹配片段的鍵值對零远。
$route.query
對象苗分,包含路由中query參數(shù)的鍵值對。如“......牵辣?name=qq&age=18”
會得到{“name”:"qq"摔癣,“age”:18}
。
$route.name
當前路徑的名字纬向,如果沒有使用具名路徑择浊,則名字為空。
$route.router
路由規(guī)則所述的路由器(以及所屬的組件)逾条。
$route.matched
數(shù)組琢岩,包含當前匹配的路徑中所包含的所有片段所對應的配置參數(shù)對象。
相關源碼:
Vue.mixin({
beforeCreate () {
if (isDef(this.$options.router)) {
this._routerRoot = this // this指向vue實例
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)
},
// ...
})
Object.defineProperty(Vue.prototype, '$route', {
get () { return this._routerRoot._route }
})
// 給Vue.prototype對象添加$route屬性膳帕,添加屬性為 this._routerRoot._route
由于this._routerRoot._route
是動態(tài)的粘捎,哪個路由對象處于活躍,就把就把活躍的路由對象賦給this._routerRoot._route
危彩,因此this.$route
代表當前活躍的路由對象攒磨。
三、總結(jié)
$router
是new Router
的實例汤徽,是全局路由對象娩缰,用于進行路由跳轉(zhuǎn)等操作;
$route
是路由信息對象谒府,表示當前活躍的路由對象拼坎,用于讀取路由參數(shù);
簡單來說也就是完疫,操作找$router
泰鸡,讀參找$route
。