const router = new VueRouter({
    scrollBehavior (to,from,savedPosition) { //路由滚动行为
        if(savedPosition){
            return savedPosition
        }else{
            const position = {}
            if(to.hash){
                position.selector = to.hash
            }
            if(to.matched.some(m=>m.meta.scrollToTop)){
                position.x = 0
                position.y = 0
            }
            // return position
            return new Promise((resolve,reject)=>{
                setTimeout(() => {
                    resolve(position)
                }, 500);
            })
        }
    },
  routes: [
    {
      path: '/foo',
      component: () => import(/* webpackChunkName: "group-foo" */ './Foo.vue') //异步路由,
      //第三
      beforeEnter: (to, from, next) => {
        // ...
      },
      meta: { requiresAuth: true } //路由元信息配置权限相关
    }
  ]})

//第一
router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // this route requires auth, check if logged in
    // if not, redirect to login page.
    if (!auth.loggedIn()) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    next() // 确保一定要调用 next()
  }
})
//第五
router.beforeResolve((to,from,next)=>{


})
//第六
router.afterEach((to, from) => {

})


//组件内路由
//第四
beforeRouteEnter (to, from, next) {
  // 在渲染该组件的对应路由被 confirm 前调用
  // 不!能!获取组件实例 `this`
  // 因为当守卫执行前,组件实例还没被创建
  next(vm => {
        // 通过 `vm` 访问组件实例
    })
},
// 第二
beforeRouteUpdate (to, from, next) {
  // 在当前路由改变,但是该组件被复用时调用
  // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
  // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
  // 可以访问组件实例 `this`
    // just use `this`
      this.name = to.params.name  next()
},
//第七
beforeRouteLeave (to, from, next) {
  // 导航离开该组件的对应路由时调用
  // 可以访问组件实例 `this`
 const answer = window.confirm('Do you really want to leave? you have unsaved changes!')
  if (answer) {
    next()
  } else {
    next(false)
  }
}
//组件过度动效
<!-- 使用动态的 transition name -->
<transition :name="transitionName">
  <router-view></router-view>
</transition>
watch: {
  '$route' (to, from) {
    const toDepth = to.path.split('/').length    
    const fromDepth = from.path.split('/').length    
    this.transitionName = toDepth < fromDepth ? 'slide-right' : 'slide-left'
}}


上一篇:VUE学习笔记十五:v-model,计算属性和侦听器

下一篇:VUE学习笔记十七:Webpack