一、$router
router是VueRouter的一个对象,通过Vue.use(VueRouter)和VueRouter构造函数得到一个router的实例对象,这个对象中是一个全局的对象,他包含了所有的路由包含了许多关键的对象和属性。
$router.push
// 字符串
this.$router.push('home')
// 对象
this.$router.push({ path: 'home' })
// 命名的路由
this.$router.push({ name: 'user', params: { userId: 123 }})
// 带查询参数,变成 /register?plan=123
this.$router.push({ path: 'register', query: { plan: '123' }})
$router.go
// 页面路由跳转 前进或者后退
this.$router.go(-1) // 后退
$router.replace
//push方法会向 history 栈添加一个新的记录,而replace方法是替换当前的页面,
不会向 history 栈添加一个新的记录
<router-link to="/05" replace>05</router-link>
// 一般使用replace来做404页面
this.$router.replace('/')
二、$route
route是一个跳转的路由对象,每一个路由都会有一个route对象,是一个局部的对象,可以获取对应的name,path,params,query等
$route.path
字符串,等于当前路由对象的路径,会被解析为绝对路径,如 "/home/news" 。
$route.params
对象,包含路由中的动态片段和全匹配片段的键值对
$route.query
对象,包含路由中查询参数的键值对。例如,对于 /home/news/detail/01?favorite=yes ,会得到$route.query.favorite == 'yes' 。
$route.router
路由规则所属的路由器(以及其所属的组件)。
$route.matched
数组,包含当前匹配的路径中所包含的所有片段所对应的配置参数对象。
$route.name
当前路径的名字,如果没有使用具名路径,则名字为空。
$route.hash**
当前路由的 hash 值 (不带 #) ,如果没有 hash 值,则为空字符串。锚点
$route.fullPath**
完成解析后的 URL,包含查询参数和 hash 的完整路径。
$route.meta
路由元信息
route object 出现在多个地方:
- 在组件内,即 this.$route
- 在 $route 观察者回调内 router.match(location) 的返回值
- 导航守卫的参数:
router.beforeEach((to, from, next) => {
// to 和 from 都是 路由信息对象
})
watch: {
$route(to, from) {
// to 和 from 都是 路由信息对象
}
}