codecamp

router.beforeEach

router.beforeEach(hook)

添加一个全局的前置钩子函数,这个函数会在路由切换开始时调用。调用发生在整个切换流水线之前。如果此钩子函数拒绝了切换,整个切换流水线根本就不会启动。

你可以注册多个全局的前置钩子函数。这些函数会按照注册的顺序被调用。调用是异步的,后一个函数会等待前一个函数完成后才会被调用。

参数

  • hook {Function}

    此钩子函数一个类型为切换对象的参数。

Example

简单示例

router.beforeEach(function (transition) {
  if (transition.to.path === '/forbidden') {
    transition.abort()
  } else {
    transition.next()
  }
})

使用 Promise 和 ES6

router.beforeEach(function ({ to, next }) {
  if (to.path === '/auth-required') {
    // 返回一个断定会 true 或者 false 的 Promise
    return AuthService.isLoggedIn()
  } else {
    next()
  }
})
router.alias
router.afterEach
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }