1

I have a navbar component, I need to redirect to the login component inside a logout method declared at navbar.

I tried: this.$router.push({name:'MyLogin'});

But I see the error:

vue-router.esm.js?8c4f:1897 TypeError: Cannot read property '$router' of undefined
at eval (main.js?56d7:68)

How can I use router push inside a component?

Or how can I inside this component make access to the router.

EDIT :

At the file: /src/router.js I have the Login route:

export default new Router({
    mode: 'history',
    routes: [
    {
        path: '/login',
        name: 'Login',
        component: LoginView
    },

And at the file: /src/components/Navibar.vue I have the doLogout method:

methods: {
    doLogout(){ 
    this.$router.push({name:'Login'}); 
}

Being new to Vue js I tried this:

doLogout(){
   const router = new router({
    routes: [
              { 
                path: '/login', 
                name: 'Login', 
                component: LoginView 
              }               
        ]
  })
 this.$router.push({name:'Login'}); 

}

I see the error message:

doLogout catch ReferenceError: LoginView is not defined at eval (VM2993 NaviBar.vue:324)

So I tried to add the component:

Vue.component('LoginView', require('Login.vue'));

Which gives me the error:

Module not found: Error: Can't resolve 'Login.vue'

Maybe I am doing the wrong steps?

Which is the correct way to enable this.$router.push() inside one component redirecting to another component?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Ângelo Rigo
  • 2,039
  • 9
  • 38
  • 69

1 Answers1

2

Try declaring as below :

At the file: /src/router.js

const router = new Router({
    mode: 'history',
    routes: [
    {
        path: '/login',
        name: 'Login',
        component: LoginView
    },
export default router

The router variable declared is accessible over all vue components.

Hence at the file: /src/components/Navibar.vue doLogout method :

methods: {
    doLogout(){ 
    this.$router.push({name:'Login'}); 
}
Riddhi
  • 2,174
  • 1
  • 9
  • 17
  • It will be : const router = new Router({ mode: 'history', routes: [ { path: '/login', name: 'Login', component: LoginView } }) export default router ?? – Ângelo Rigo Jun 07 '19 at 14:54
  • thank´s @Riddhi, now debuging i see the entire router object, this is at the navbar component, just don´t know why it stays on the same page, it does not redirect. – Ângelo Rigo Jun 07 '19 at 15:26