Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go to a specific route in Vuejs 2

I'm new in VueJS, I'm using VueJS 2 Webpack template. I was trying to redirect from login component to home component if login successful, I've tried many things but I still getting errors. Here is my routing:

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')
      }
    }
  }]
})

And that's what I tried to get redirected to home component:

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

And I got this error:

Uncaught (in promise) TypeError: Cannot read property 'name' of undefined(…)
like image 707
jemlifathi Avatar asked Dec 15 '16 14:12

jemlifathi


1 Answers

this.$router.replace() expects a location.

this.$router.go('/') travels through the browser history so it shouldn't actually return anything. It's essentially like window.history.go(Number).

You likely want to do this.$router.replace('/') if you want to replace the page you're on.

Also. I'd check out this part of the documentation. You can put a lot of your repetitive code in a beforeEach.

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

like image 191
Bill Criswell Avatar answered Sep 21 '22 04:09

Bill Criswell