vue-router

vue-router 默认 hash 模式 —— 使用 URL 的 hash 来模拟一个完整的 URL,于是当 URL 改变时,页面不会重新加载。
1、Vue Router 是 Vue.js 官方的路由管理器。
2、用 Vue.js + Vue Router 创建单页应用,是非常简单的。
使用 Vue.js ,我们已经可以通过组合组件来组成应用程序,
当你要把 Vue Router 添加进来,我们需要做的是,
将组件 (components) 映射到路由 (routes),然后告诉 Vue Router 在哪里渲染它们。
3、通过注入路由器,我们可以
在任何组件内通过 this.$router 访问路由器,window.history.length > 1 ? this.$router.go(-1) : this.$router.push('/')
也可以通过 this.$route 访问当前路由 this.$route.params.username
除了 $route.params 外,$route 对象还提供了其它有用的信息,
例如,$route.query (如果 URL 中有查询参数)、$route.hash
4、提醒一下,当使用路由参数时,例如从 /user/foo 导航到 /user/bar,原来的组件实例会被复用。
因为两个路由都渲染同个组件,比起销毁再创建,复用则显得更加高效。不过,这也意味着组件的生命周期钩子不会再被调用。
复用组件时,想对路由参数的变化作出响应的话,你可以简单地 watch (监测变化) $route 对象
5、嵌套路由
routes: [
{
path: '/user/:id',
component: User,
name: 'user',
children: [
// 当 /user/:id 匹配成功,
// UserHome 会被渲染在 User 的 <router-view> 中
{ path: '', component: UserHome },

// ...其他子路由
]
}
]
6、编程式导航
router.push({})
router.go()
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
// 带查询参数,变成 /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})
7、window.vue.$router.addRoutes
8、重定向
从 /a 重定向到 /b
{ path: '/a', redirect: '/b' }
{ path: '/a', redirect: { name: 'foo' }}
9、路由组件传参
10、导航守卫
1、全局前置守卫
router.beforeEach((to, from, next) => {
if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })
else next()
})
2、路由独享的守卫
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
beforeEnter: (to, from, next) => {
// ...
}
}
]
})
3、组件内的守卫
beforeRouteEnter---组件实例还没被创建
beforeRouteUpdate (2.2 新增)
beforeRouteLeave---// 导航离开该组件的对应路由时调用
11、路由元信息
定义路由的时候可以配置 meta 字段
component: Bar,
// a meta field
meta: { requiresAuth: true }
12、滚动行为
使用前端路由,当切换到新路由时,想要页面滚到顶部,
或者是保持原先的滚动位置,就像重新加载页面那样。
vue-router 能做到,而且更好,它让你可以自定义路由切换时页面如何滚动。
const router = new VueRouter({
routes: [...],
scrollBehavior (to, from, savedPosition) {
// return 期望滚动到哪个的位置
}
})
13、路由懒加载---当打包构建应用时,JavaScript 包会变得非常大,影响页面加载。
如果我们能把不同路由对应的组件分割成不同的代码块,然后当路由被访问的时候才加载对应组件,这样就更加高效了。
结合 Vue 的异步组件和 Webpack 的代码分割功能,轻松实现路由组件的懒加载。
const Foo = () => import(/* webpackChunkName: "group-foo" */ './Foo.vue')
const Bar = () => import(/* webpackChunkName: "group-foo" */ './Bar.vue')

原文地址:https://www.cnblogs.com/yangyutian/p/13213592.html