amelihovv
@amelihovv
Фулстек веб разработчик

Vue.js Как записать сообщение об ошибке в хуке beforeRouteEnter компонента?

Я использую vue@2.0, vue-router@2.0, vue-resource@1.0.3.

У меня есть компонент регистрации:
export default {
    data() {
      return {
        name: null,
        email: null,
        password: null,
        success: false,
        errors: {},
        error: null,
        roles: [],
      }
    },
    beforeRouteEnter (to, from, next) {
      Role.get().then(response => {
        next(vm => {
          vm.roles = response.body.data
          vm.error = null
        })
      }, response => {
        this.error = 'Cannot fetch roles' // 'this' is undefined here

        next(false)
      })
    },
    watch: {
      $route () {
        Role.get().then(response => {
          next(vm => {
            vm.roles = response.body.data
            vm.error = null
          })
        }, response => {
          this.error = 'Cannot fetch roles' // 'this' is undefined here too

          next(false)
        })
      },
    },
  }

Я хочу сделать так, чтобы если не удалось получить список ролей с апи, то в поле error компонента записалось сообщение об ошибке, и переход на страницу регистрации при этом не произошел (т. е. вызвался next(false)).
  • Вопрос задан
  • 432 просмотра
Решения вопроса 1
k12th
@k12th
console.log(`You're pulling my leg, right?`);
router.vuejs.org/en/advanced/navigation-guards.html

The beforeRouteEnter guard does NOT have access to this ...
However, you can access the instance by passing a callback to next


То есть как-то так:
beforeRouteEnter (to, from, next) {
    Role.get().then(response => {
        next(vm => {
            vm.roles = response.body.data
            vm.error = null
        })
    }, response => {
        next(vm => {
            vm.error = 'Cannot fetch roles'
        })
    })
}
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы