跳转至

$router与$route

router与route的参数对比

img

$router

是什么?

$router是VueRouter的实例,我们可以在任何地方使用它。

常用方法:

作为全局路由对象,它包含了许多属性。譬如:history对象。

this.$router.push('/user')  // 跳转路由
this.$router.replace('/user')   // 跳转路由,但是不会有记录,不入栈。

$route

是什么?

$route表示当前正在跳转的路由对象。包含路由相关信息,如path,name,meta 等

常用:

  1. 使用params传递参数
//  使用带params的路由跳转
this.$router.push({name:'user',params:{id:1}})
//  对应取参
this.$route.params.id

注:使用params进行传参时,只能使用name,不然取参取不到,圈起来,要考的~

  1. 在path中进行配置(与params类似)
this.$router.push(`/user/${userId}`)
// 这时路由需要进行特殊配置
   {
     path: '/user/:userId',
     name: 'user',
     component: components['user']
   }
//  对应取参
this.$route.params.id
  1. 使用query
//  使用query
this.$router.push({path: '/user',query:{userId:2}}) 

//  对应取参
this.$route.query   // get请求url后面带的查询参数

params与query使用区别

  • url上 params方式,在url中不会将传递的参数进行显示,类似于post,相对安全。 query方式,在url中会将传递的参数进行展示,类似于get,不安全。
  • 用法 params需要用name引入,query需要path引入。