vue中的route和router各自是什么以及之间的区别
共同点
- 使用时都需要加上
$
.- 原因: 因为在vue-router的源码中,vue-router和vue-route是被注册为了全局组件,在注册的时候,就是以
$router
和$route
的名字命名的. - 源码:给Vue实例原型上注册了
$route
和$router
两个全局组件 - 使用时,需要添加
$
符号.
- 原因: 因为在vue-router的源码中,vue-router和vue-route是被注册为了全局组件,在注册的时候,就是以
不同点
id | name | attr |
---|---|---|
1 | route | 当前被激活的路由地址信息(包含fallpath、query等信息) |
1 | router | 全局的路由器对象(具有push、replace、go、back、forward等方法实现路由跳转) |
1、route
-
route信息:
-
可以从中获取到路由信息,包括当前激活的路由地址,路由中的query参数.
-
获取方法:
this.$route.params.id// 获取当前路由query参数中的id
this.$route.fullpath// 获取当前路由的完整地址
2、 router
- router信息.
- router的作用: 可以进行路由跳转,其中具体的方法有:
- push() :相当于Html5中的history.pushState()方法,将当前路由压入.
- replace() : 相当于Html5中的history.replace()方法,将当前路由替换.
- go(): 相当于Html5中的history.go()方法,当参数为1时,前进一个.参数为-1时,后退一个.
- back():相当于Html5中的history.back()方法,向后回退一个.
- forward():相当于Html5中的history.forward()方法,向前前进一个.
- router还可以携带路由中的query(有两种方法).
- 传递参数方法一:
1、配置: 使用params,在路由表的path后面添加/:id
参数.
- 传递参数方法一:
{
path:'/home/:id',
component:Home
},
2、获取: 在跳转后的页面上使用javascript $router.params.id
或this.$router.params.id
进行获取
- 传递参数方法二:
配置: 在跳转的时候
this.$router.push({
path:'/home',query:{
id;1,name:'Dawn'}})
2、 获取:
this.$route,params.id // 获取参数query