理理Vue细节(推荐)

2020-06-13 10:33:58易采站长站整理

17. 路由

区分:this.$router指路由器,this.$route指当前路由

通配符:捕获所有路由或 404 Not found路由


// 含通配符的路由都要放在最后,因为优先级由定义顺序决定
{
// 会匹配所有路径
path: '*'
}
{
// 会匹配以 `/user-` 开头的任意路径
path: '/user-*'
}

当使用一个通配符时,$route.params内会自动添加一个名为 pathMatch 参数。它包含了 URL 通过通配符被匹配的部分:


// 给出一个路由 { path: '/user-*' }
this.$router.push('/user-admin')
this.$route.params.pathMatch // 'admin'
// 给出一个路由 { path: '*' }
this.$router.push('/non-existing')
this.$route.params.pathMatch // '/non-existing'

点击 <router-link :to=”…”> 等同于调用 router.push(…)方法,因为<router-link>会在内部调用该方法,进而在history栈添加一个新的记录

使用了push时,如果提供的path不完整,则params会被忽略,需要提供路由的 name 或手写完整的带有参数的 path:


const userId = '123'
router.push({ name: 'user', params: { userId }}) // -> /user/123
router.push({ path: `/user/${userId}` }) // -> /user/123
// 这里的 params 不生效
router.push({ path: '/user', params: { userId }}) // -> /user

router.push/router.replace/router.go 效仿于 window.history.pushState/window.history.replaceState/window.history.go

命名视图:router-view可设置名字,如果router-view没有设置名字,那么默认为 default


<router-view></router-view>
<router-view name="a"></router-view>
<router-view name="b"></router-view>

const router = new VueRouter({
routes: [
{
path: '/',
components: {
default: Foo,
a: Bar,
b: Baz
}
}
]})

路由使用props:可将路由参数设置为组件属性


const User = {
props: ['id'],
template: '<div>User {{ id }}</div>'
}
// 通过布尔值设置
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User, props: true },

// 对于包含命名视图的路由,你必须分别为每个命名视图添加 `props` 选项:
{
path: '/user/:id',
components: { default: User, sidebar: Sidebar },
props: { default: true, sidebar: false }
}
]})

// 通过函数设置query
// URL /search?q=vue 会将 {name: 'vue'} 作为属性传递给 SearchUser 组件
const router = new VueRouter({
routes: [
{ path: '/search', component: SearchUser, props: (route) => ({ name: route.query.q }) }