【问题标题】:Using this.$router in a Laravel/Vue.js component在 Laravel/Vue.js 组件中使用 this.$router
【发布时间】:2020-08-07 01:50:51
【问题描述】:

我在 Laravel 中有一个 Vue.js 组件,它正在加载:

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

但是,当我在其中使用 this.$router.go() 时,出现以下错误:

TypeError: 无法读取未定义的属性“$router”

所以,我已将此添加到我的routes

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

然后,我明白了:

未捕获的引用错误:未定义用户配置文件

所以,我换了:

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

作者:

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

【问题讨论】:

  • 分享你使用this.$router.go()的代码?
  • @RishiRaut 我刚刚更新了我的帖子。
  • 如@RishiRaut所说,使用箭头功能,别忘了将vue-router注册到vue instance,这样你就可以访问this.$router以及当前路由this.$route

标签: laravel vue.js vue-router


【解决方案1】:

要么使用箭头函数

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

Read about arrow function

【讨论】:

  • 太棒了!并感谢有关箭头功能的链接!
猜你喜欢
  • 2018-04-09
  • 2018-02-14
  • 2020-04-14
  • 2018-10-07
  • 2021-06-02
  • 2016-05-26
  • 2020-09-21
  • 2016-11-08
  • 2017-05-21
相关资源
最近更新 更多