Skip to content

Vue 中$route和$router 的区别

很多初学 vue 的人搞不明白 this.$route 和 this.$router 的区别,不明白什么时候用$route 什么时候用$router,今天记录一个区分方法:

什么是$route?

route 是一个跳转路由的对象,每一个路由都会有一个 route 对象,是一个局部对象,可以获取对应的 name ,path ,params,query 等

附: query 和 params 传参的区别

json
{
  "fullPath": "/detail/8"
  "hash": ""
  "matched": [{}]
  "meta": {show: true}
  "name": undefined
  "params": {skuid: '8'}
  "path": "/detail/8"
  "query": {}
  ···
}

什么是$router?

router 是 VueRouter 的一个实例对象,是一个全局对象,它包含了所有路 i 有包含了许多关键的对象和属性。

json
{
  ...
  [[Prototype]]:{
    "addRoute": ƒ addRoute(parentOrRoute, route)
    "addRoutes": ƒ addRoutes(routes)
    "afterEach": ƒ afterEach(fn)
    "back": ƒ back()
    "beforeEach": ƒ beforeEach(fn)
    "beforeResolve": ƒ beforeResolve(fn)
    "forward": ƒ forward()
    "getMatchedComponents": ƒ getMatchedComponents(to)
    "getRoutes": ƒ getRoutes()
    "go": ƒ go(n)
    "init": ƒ init(app /* Vue component instance */)
    "match": ƒ match(raw, current, redirectedFrom)
    "onError": ƒ onError(errorCb)
    "onReady": ƒ onReady(cb, errorCb)
    "push": ƒ (loaction)
    "replace": ƒ (loaction)
    "resolve": ƒ resolve( to, current, append )
    "constructor": ƒ VueRouter(options)
    "currentRoute": (...)
    "get currentRoute": ƒ ()
  }
}

如果想获取路由本身的信息,比如获取当前 url 当前的 params 参数,query 参数,使用 this.$route 进行获取即可。

如果想要对路由进行跳转,返回等操作,使用 this.$router 操作即可。