Перейти к определенному маршруту в Vuejs 2

Я новичок в VueJS, использую шаблон VueJS 2 Webpack. Я пытался перенаправить с компонента входа в систему на домашний компонент, если вход в систему прошел успешно, я пробовал много вещей, но все равно получаю ошибки. Вот моя маршрутизация:

const router = new VueRouter({
  mode: 'history',
  routes: [{
    'name': 'home',
    path: '/',
    component: require('./components/Home.vue'),
    beforeEnter: (to, from, next) => {
      if (!localStorage.getItem('user')) {
        next('/login')
      }
    }
  }, {
    'name': 'profile',
    path: '/profile',
    component: require('./components/Profile.vue'),
    beforeEnter: (to, from, next) => {
      if (!localStorage.getItem('user')) {
        next('/login')
      }
    }
  }, {
    'name': 'login',
    path: '/login',
    component: require('./components/Login.vue')
  }, {
    'name': 'new',
    path: '/new',
    component: require('./components/New.vue'),
    beforeEnter: (to, from, next) => {
      if (!localStorage.getItem('user')) {
        next('/login')
      }
    }
  }, {
    'name': 'signup',
    path: '/signup',
    component: require('./components/Signup.vue')
  }, {
    'name': 'logout',
    path: '/logout',
    beforeEnter: (to, from, next) => {
      localStorage.removeItem('user')
      next('/login')
    }
  }, {
    'name': 'article',
    path: '/article/:id',
    component: require('./components/Article.vue'),
    beforeEnter: (to, from, next) => {
      if (!localStorage.getItem('user')) {
        next('/login')
      }
    }
  }]
})

И это то, что я пытался перенаправить на домашний компонент:

this.$router.replace(this.$router.go('/'))

И я получил эту ошибку:

Uncaught (in promise) TypeError: Cannot read property 'name' of undefined(…)

person jemlifathi    schedule 15.12.2016    source источник


Ответы (1)


this.$router.replace() ожидает местоположение.

this.$router.go('/') путешествует по истории браузера, поэтому на самом деле ничего не должно возвращаться. По сути, это как window.history.go(Number).

Вы, вероятно, захотите сделать this.$router.replace('/'), если хотите заменить страницу, на которой находитесь.

Также. Я бы проверил эту часть документации. Вы можете поместить много повторяющегося кода в файл beforeEach.

https://router.vuejs.org/en/advanced/meta.html

person Bill Criswell    schedule 15.12.2016
comment
Совершенно никаких проблем! - person Bill Criswell; 15.12.2016