2

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);
        });
    }
  },
3
  • share code where you used this.$router.go() ? Commented Apr 23, 2020 at 16:35
  • @RishiRaut I've just updated my post. Commented Apr 23, 2020 at 16:37
  • as @RishiRaut said use arrow function and dont forget to register the vue-router to vue instance so that you can access this.$router as well as the current route as this.$route Commented Apr 23, 2020 at 16:48

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Great! And thanks for the link about arrow function!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.