Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
        }
    }
}
like image 591
sudo Avatar asked Oct 27 '17 21:10

sudo


1 Answers

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>
like image 72
Arian Saputra Avatar answered Sep 23 '22 21:09

Arian Saputra