Vue Router

The official router for Vue.js.

Posted by Dusign on 2020-02-23
Words 836 and Reading Time 3 Minutes
Viewed Times

Vue Router is the official router for Vue.js. It deeply integrates with Vue.js core to make building Single Page Applications with Vue.js a breeze. For most Single Page Applications, it’s recommended to use the officially-supported vue-router library.

路由跳转

Vue.js 中做项目的时候需要点击父组件中的某个内容之后跳转到子组件中,方法如下:

  1. this.$router.push({name: 'ROUTER_NAME', params: { KEY: VALUE }})
    注意使用之前要提前设置好 router,其中 name 也可以换成 path,与 router 中的数据对应即可。

  2. this.$router.replace('/PATH')

传递参数

有时候路由跳转的时候父组件需要给子组件传递参数,这时候就需要在路由中携带参数,然后在子组件中从路由中获取相应的参数,方法如下:

1、通过 $router.pushpath 后面传递参数,父组件写法如下

1
2
3
this.$router.push({
path: `/PATH/${PARAMS_KEY}`,
})

然后在路由中配置如下
1
2
3
4
5
{
path: '/PATH/:PARAMS_KEY',
name: 'NAME',
component: COMPONENT
}

这种方法需要在 path 中添加 /:PARAMS_KEY 来对应 $router.pushpath 所携带的参数,然后在子组件中可以使用如下方法来获取传递的参数值。
1
this.$route.params.PARAMS_KEY

2、通过 $router.push 中的 name 匹配路由,通过 params 来传递参数,父组件写法如下

1
2
3
4
5
6
this.$router.push({
name: 'NAME',
params: {
KEY: VALUE
}
})

然后在路由中配置如下
1
2
3
4
5
{
path: '/PATH',
name: 'NAME',
component: COMPONENT
}

子组件中通过如下方法来获取参数
1
this.$route.params.KEY

3、通过 $router.push 中的 path 来匹配路由,通过 query 来传递参数,父组件写法如下

1
2
3
4
5
6
this.$router.push({
path: '/PATH',
query: {
KEY: VALUE
}
})

然后在路由中配置如下
1
2
3
4
5
{
path: '/PATH',
name: 'NAME',
component: COMPONENT
}

子组件中通过如下方法来获取参数
1
this.$route.query.KEY

这种方法下 query 中传递的参数会显示在 url 后面,类似于 get 请求的 url 中的参数。

route and router

routerVueRouter 的一个对象,通过 Vue.use(VueRouter)VueRouter 构造函数得到一个 router 的实例对象,这是一个全局的对象,他包含了所有的路由包含了许多关键的对象和属性。

history 对象

  1. $router.push({path:'PATH'}) 是向 history 栈中添加一个路由,我们看来是切换路由,但本质是在添加一个 history 记录,此时 window.history.length 会 +1
  2. $router.replace({path:'PATH'}) 是替换路由,没有历史记录,window.history.length 不会 +1

route 是一个跳转的路由对象,每一个路由都会有一个 route 对象,是一个局部的对象,可以获取对应的 namepathparamsquery

$route.path 是一个字符串,等于当前路由对象的路径,会被解析为绝对路径

$route.params 是一个对象,包含路由中的动态片段和全匹配片段的键值对

$route.query 是一个对象,包含路由中查询参数的键值对。例如,对于 /home/news/detail/01?favorite=yes ,会得到 $route.query.favorite == 'yes'

$route.router 是路由规则所属的路由器(以及其所属的组件)

$route.matched 是一个数组,包含当前匹配的路径中所包含的所有片段所对应的配置参数对象

$route.name 是当前路径的名字,如果没有使用具名路径,则名字为空


If you like this blog or find it useful for you, you are welcome to comment on it. You are also welcome to share this blog, so that more people can participate in it. If the images used in the blog infringe your copyright, please contact the author to delete them. Thank you !

...

...

00:00
00:00