19/3/31学习笔记

4次阅读

共计 1967 个字符,预计需要花费 5 分钟才能阅读完成。

vue-router1 router-link 导航到不同组件 <router-link to=”/foo”>Go to Foo</router-link> <router-link to=”/bar”>Go to Bar</router-link> 定义路由 const routes = [{ path: ‘/foo’, component: Foo}, {path: ‘/bar’, component: Bar}] 当 <router-link> 对应的路由匹配成功,将自动设置 class 属性值 .router-link-active
2 动态路由匹配 routes: [
// 动态路径参数 以冒号开头
{path: ‘/user/:id’, component: User}
]3 嵌套路由,在组件中还包含多个子组件且存在路由跳转 routes: [
{path: ‘/user/:id’, component: User,
children: [
{
// 当 /user/:id/profile 匹配成功,
// UserProfile 会被渲染在 User 的 <router-view> 中
path: ‘profile’,
component: UserProfile
},
{
// 当 /user/:id/posts 匹配成功
// UserPosts 会被渲染在 User 的 <router-view> 中
path: ‘posts’,
component: UserPosts
}
]
}
]
4 编程式导航 除了可以通过 <router-link to: > 跳转,还可以通过 this.$router.push() 的方式跳转(注意 path 的方式,params 不能生效)// 字符串 router.push(‘home’)
// 对象 router.push({path: ‘home’})
// 命名的路由 router.push({name: ‘user’, params: { userId: ‘123’}})
// 带查询参数,变成 /register?plan=privaterouter.push({path: ‘register’, query: { plan: ‘private’}}) 注意:如果提供了 path,params 会被忽略,上述例子中的 query 并不属于这种情况。取而代之的是下面例子的做法,你需要提供路由的 name 或手写完整的带有参数的 path:const userId = ‘123’router.push({name: ‘user’, params: { userId}}) // -> /user/123router.push({path: /user/${userId} }) // -> /user/123// 这里的 params 不生效 router.push({path: ‘/user’, params: { userId}}) // -> /user
this.$router.replace() router.replace(location, onComplete?, onAbort?) 跟 router.push 很像,唯一的不同就是,它不会向 history 添加新记录,而是跟它的方法名一样 —— 替换掉当前的 history 记录。
5 重定向
重定向
重定向也是通过 routes 配置来完成,下面例子是从 /a 重定向到 /b:
const router = new VueRouter({routes: [
{path: ‘/a’, redirect: ‘/b’}
]}) 重定向的目标也可以是一个命名的路由:
const router = new VueRouter({routes: [
{path: ‘/a’, redirect: { name: ‘foo’}}
]})
6 导航守卫 全局前置守卫你可以使用 router.beforeEach 注册一个全局前置守卫:
const router = new VueRouter({…})
router.beforeEach((to, from, next) => {// …})
完整的导航解析流程导航被触发。在失活的组件里调用离开守卫。调用全局的 beforeEach 守卫。在重用的组件里调用 beforeRouteUpdate 守卫 (2.2+)。在路由配置里调用 beforeEnter。解析异步路由组件。在被激活的组件里调用 beforeRouteEnter。调用全局的 beforeResolve 守卫 (2.5+)。导航被确认。调用全局的 afterEach 钩子。触发 DOM 更新。用创建好的实例调用 beforeRouteEnter 守卫中传给 next 的回调函数。
7 路由元信息 定义路由的时候可以配置 meta 字段:
const router = new VueRouter({routes: [
{
path: ‘/foo’,
component: Foo,
children: [
{
path: ‘bar’,
component: Bar,
// a meta field
meta: {requiresAuth: true}
}
]
}
]})

正文完
 0