vue-router beforeEnter警卫不适用于URL更改

时间:2018-08-29 22:21:56

标签: vue-router

我有两条路径“#/ inv /:invId”和“#/ survey”。第一个将invId存储在localstorage中,以便第二个可以获取它。当我转到#/ inv / 123时,它将转发到#/ survey并运行该代码。然后,如果我将浏览器中的URL更改为#/ inv / 129,则/ inv防护程序将运行,更新本地存储,重置状态vars并尝试转发至#/ survey但未被调用,console.log不会触发。你能看到我做错了吗?还是有其他方法可以做到?最后,我希望ID在加载问卷调查后不在网址中。

{
  path: '/inv/:invId',
  name: 'SurveyInvitation',
  beforeEnter: (to, from, next) => {
    if (parseInt(to.params.invId) > 0) {
      localStorage.setItem('invId', to.params.invId)
      state.survey = {}
      state.isValidSurvey = false
      console.log('inv before enter, invId > 0', to.params.invId)
      next('/survey');
    } else {
      console.log('inv before enter, error')
      next('/error')
    }
  }
},
{
  path: '/survey',
  name: 'Survey',
  component: Survey,
  beforeEnter: (to, from, next) => {
    console.log('/survey before enter', localStorage.getItem('invId')) // not called on url change
    let invId = localStorage.getItem('invId')

    if (!parseInt(invId) > 0) { next('/error') }
    state.loadSurvey(invId)
      .then(function () {
        if (state.isValidSurvey) { next() } else { next('/error') }
      })
      .catch(function (err) {
        console.log('not loaded', err)
        next()
      })
  }
}

0 个答案:

没有答案