Использование этого. $ Router в компоненте Laravel / Vue. js - PullRequest
2 голосов
/ 23 апреля 2020

У меня есть Vue. js компонент в Laravel, он загружается с:

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

Однако, когда я использую this.$router.go() в нем, я получаю следующую ошибку:

Ошибка типа: невозможно прочитать свойство '$ router' из неопределенного

Итак, я добавил это к своему routes:

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

Но затем я получаю:

Uncaught ReferenceError: UserProfile не определен

Итак, я заменил:

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

by:

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

Но я получаю эту ошибку:

Неизвестный пользовательский элемент: - вы правильно зарегистрировали компонент?

Как мне исправить эту проблему, чтобы иметь возможность использовать this.$router.go() в моем компоненте?

=== РЕДАКТИРОВАТЬ ===

Я использую this.$router.go() здесь:

  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);
        });
    }
  },

1 Ответ

1 голос
/ 23 апреля 2020

Либо Использовать функцию стрелки

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);
        });
    }
  },

Или использовать 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);
        });
    }
  },

Читать о функции стрелки

...