VueRouter-知识点总结
返回方法
goBack () {
window.history.length > 1
? this.$router.go(-1)
: this.$router.push('/')
}
编程式导航
router.push(location, onComplete?, onAbort?)
字符串
router.push(‘home’)对象
router.push({ path: ‘home’ })命名的路由
router.push({ name: ‘user’, params: { userId: 123 }})带查询参数,变成 /register?plan=private
router.push({ path: ‘register’, query: { plan: ‘private’ }})
router.replace(location, onComplete?, onAbort?)
跟 router.push 很像,唯一的不同就是,它不会向 history 添加新记录,而是跟它的方法名一样 —— 替换掉当前的 history 记录。
router.go(n)
重定向和别名
重定向
const router = new VueRouter({
routes: [
{ path: '/a', redirect: { name: 'foo' }}
]
})
别名
const router = new VueRouter({
routes: [
{ path: '/a', component: A, alias: '/b' }
]
})
『别名』的功能让你可以自由地将 UI 结构映射到任意的 URL,而不是受限于配置的嵌套路由结构。
路由组件传参
const User = {
template: '<div>User {{ $route.params.id }}</div>'
}
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User }
]
})
使用 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 }
}
]
})
导航守卫
heyapass限制登录权限例子
router.beforeEach((to, from, next) => {
if (cookie.getToken()) { // determine if there has token
/* has token*/
if (to.path === '/login') {
next()
} else {
next()
}
} else {
/* has no token*/
if (whiteList.indexOf(to.path) !== -1) {
next('/login')
Message({
message: 'HEYAPASSのアカウントにログインしてください。',
type: 'error',
showClose:true
});
} else {
next() // 否则全部重定向到登录页
}
}
})
完整的导航解析流程
导航被触发。
在失活的组件里调用离开守卫。
调用全局的 beforeEach 守卫。
在重用的组件里调用 beforeRouteUpdate 守卫 (2.2+)。
在路由配置里调用 beforeEnter。
解析异步路由组件。
在被激活的组件里调用 beforeRouteEnter。
调用全局的 beforeResolve 守卫 (2.5+)。
导航被确认。
调用全局的 afterEach 钩子。
触发 DOM 更新。
用创建好的实例调用 beforeRouteEnter 守卫中传给 next 的回调函数。
路由元信息/滚动行为
heyapass采用路由元判断滚动行为
const scrollBehavior = (to, from, savedPosition) => {//vue-router滚动行为
if (savedPosition) {
// savedPosition is only available for popstate navigations.
return savedPosition
} else {
const position = {}
// new navigation.
// scroll to anchor by returning the selector
if (to.hash) {
position.selector = to.hash
}
// check if any matched route config has meta that requires scrolling to top
if (to.matched.some(m => m.meta.scrollToTop)) {
// cords will be used if no selector is provided,
// or if the selector didn't match any element.
position.x = 0
position.y = 0
}
// if the returned position is falsy or an empty object,
// will retain current scroll position.
return position
}
}
过渡特效
<transition>
<router-view></router-view>
</transition>
懒加载
当打包构建应用时,Javascript 包会变得非常大,影响页面加载。如果我们能把不同路由对应的组件分割成不同的代码块,然后当路由被访问的时候才加载对应组件,这样就更加高效了。
import Index from '../page/index'
->
const Index = () => import ('../page/index');