DevonDahon
DevonDahon

Reputation: 8360

Using this.$router in a Laravel/Vue.js component

I have a Vue.js component in Laravel, it's loading with:

Vue.component('user-profile', require('./components/UserProfile.vue').default);

However, when I use this.$router.go() in it, I get the following error:

TypeError: Cannot read property '$router' of undefined

So, I've add this to my routes:

const routes = [
    {
        path: '/profile',
        component: UserProfile
    },
    ...
];

But then, I get:

Uncaught ReferenceError: UserProfile is not defined

So, I replaced:

Vue.component('user-profile', require('./components/UserProfile.vue').default);

by:

import UserProfile from './components/UserProfile.vue';

But I get this error:

Unknown custom element: - did you register the component correctly?

How should I fix this issue to be able to use this.$router.go() in my component ?

=== EDIT ===

I'm using this.$router.go() here:

  methods: {
    async update () {
      await axios.put(`/api/user/` + this.data.id, this.user)
        .then(function (response) {
          console.log(response);
          this.$router.go()
        })
        .catch(function (error) {
          console.log(error);
        });
    }
  },

Upvotes: 2

Views: 122

Answers (1)

Niklesh Raut
Niklesh Raut

Reputation: 34924

Either Use arrow function

methods: {
    async update () {
      await axios.put(`/api/user/` + this.data.id, this.user)
        .then((response) => { // check here
          console.log(response);
          this.$router.go()
        })
        .catch((error) => {
          console.log(error);
        });
    }
  },

Or use var vm = this;

 methods: {
    async update () {
      var vm = this;// check here
      await axios.put(`/api/user/` + this.data.id, this.user)
        .then(function (response) {
          console.log(response);
          vm.$router.go(); // check here
        })
        .catch(function (error) {
          console.log(error);
        });
    }
  },

Read about arrow function

Upvotes: 1

Related Questions