首页 > 解决方案 > 如何在 VueJS 的 SetTimeOut 中提交存储

问题描述

我正在使用 Vue.js 在 Laravel 中制作应用程序。我想在触发方法时等待两秒钟,然后执行存储操作。但是,当我实现它时,我收到一个错误。

这是我的代码:

.listen('TeamLeaving', e => {
  setTimeout(function() {
    axios.get('/api/team/' + e.team.id + '/pulse').then(response => {
      if (response.data === 0) {
        // here is where it messes up
        this.$store.commit('team/REMOVE_TEAM', e.team)
      }
    })
  }, 2000)

  // this.$store.commit('team/REMOVE_TEAM', e.team);
})

但是我收到一个错误:

Uncaught (in promise) TypeError: Cannot read property 'commit' of undefined

当我在它之外进行提交时,setTimeout它工作得很好。所以我假设setTimeout. 有人可以帮我解决这个问题吗?

标签: laravelvue.jstimeout

解决方案


这篇文章可能会对您有所帮助:如何在 vueJs 方法中设置超时

重要的一点:

thisin 匿名函数附加到该匿名函数而不是您的主函数

你可以试试这个:

.listen('TeamLeaving', (e) => {
                    let vm = this;
                    setTimeout(function () {
                        axios.get('/api/team/'+ e.team.id + '/pulse')
                            .then(response => {

                                if (response.data === 0) {
                                    //here is where it messes up
                                    vm.$store.commit('team/REMOVE_TEAM', e.team)
                                }
                            });


                    }, 2000);

                    // this.$store.commit('team/REMOVE_TEAM', e.team);

                });

推荐阅读