vue.js this.$router undefined

I am getting undefined for

this.$router

undefined in App.vue and other components. I couldn't find a solution.

here a part of my main.js

Vue.use(VueRouter);
Vue.use(VueResource);

const router = new VueRouter({
    routes: Routes,
    mode: 'history'
});

new Vue({
    el: '#app',
    render: h => h(App),
    router
});

and here my router.js which I am importing in main.js.

export default [
    {path: '/', component: Home, name: 'home'},
    {path: '/home', component: Home, name: 'home2'},
    {path: '/user/login', component: Login, name: 'userLogin'}
];

Thank you :)

Edit

I was using it in script tags like this,

<script>
    import HeadNavBar from './components/HeadNavBar.vue';
    import SideBarNav from './components/SideBarNav.vue';
    import Home from './components/Home.vue';


    console.log(this.$router,pus); //the undefined type

    export default {
        name: 'app',
        data() {
            return {
                isLogin: true
            }
        },
        components: {
            'app-headnav': HeadNavBar,
            'app-sidebarnav': SideBarNav,
            'app-home': Home
        }

    }
</script>

but when I moved it into the method section, I got the response I wanted.

export default {
    name: 'app',
    data() {
        return {
            isLogin: true
        }
    },
    components: {
        'app-headnav': HeadNavBar,
        'app-sidebarnav': SideBarNav,
        'app-home': Home
    },methods: {
        myFunc: function() {
            console.log(this.$router,pus); // this gave result
        }
    }
}

Answers:

Answer

I can only reproduce the undefined error for this.$router when using an arrow function (perhaps that's what you're doing), which the Vue documentation recommends against:

Don’t use arrow functions on an options property or callback, such as created: () => console.log(this.a) or vm.$watch('a', newValue => this.myMethod()). Since arrow functions are bound to the parent context, this will not be the Vue instance as you’d expect, often resulting in errors such as Uncaught TypeError: Cannot read property of undefined or Uncaught TypeError: this.myMethod is not a function.

Here's an example of the mounted callback logging this.$router successfully:

<script>
  export default {
    name: 'app',

    // DON'T USE ARROW FUNCTIONS HERE
    // mounted: () => {
    //   console.log({router: this.$router});
    // },

    mounted() {
      console.log({router: this.$router});
    }
  }
</script>
Answer

The console.log(this.$router,pus) above the export is executed when import the component. It happened before the component was created. So this is just a empty object {}.

You should get the this.$router inside the methods of export object.

Answer

I know this is old, but I am gonna share something I ran into and how I got around it in case someone is struggling out there.

My scenario is a vue/meteor project.

In functions/handlers, "this" refers to the function's target, so this.$router is looking for $router within the function or the target itself.

    ///////DOESN'T WORK ///////////
  mounted: function () {
    $(document).on('click', '.element', function(){
             //this is recognized as 
             this.$router.push(PATH)
        });
  },


    ////////THIS WORKS//////////
  mounted: function () { 
    //make router defined outside of function.
    var navigate = this.$router;

     $(document).on('click', '.element', function(){
        navigate.push(PATH)
     });
  }
Answer

we have a same error, in this case i have fixed that, i just import the router files in my component like this and it's working:

import router files/configuration in my component :

import router from '../router'

and i can use that like this :

router.replace('home')

and that's should be working

my full code :

<script>
import router from '../router'
export default {
  methods: {
  signIn: function () {
    firebase
    .auth().signInWithEmailAndPassword(this.email, this.password).then(
      function (user) {
        router.replace('home')
      },
      function (err) {
        alert('Maaf, ' + err.message)
      }
    )
  }
 }
}
</script>

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.