如何提交存储在 VueJS 的 SetTimeOut 中
How to commit to store within a SetTimeOut in VueJS
我正在 Laravel 使用 Vue.js 制作应用程序。我想在触发方法时等待两秒钟,然后执行存储操作。但是,当我实现这个时,我收到一个错误。
这是我的代码:
.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
内部有问题。有人可以帮我操纵一下吗?
这篇 post 可能会对您有所帮助:
重要的一点:
this
in anonymous function is attached to that anonymous function
not to your main function
你可以试试这个:
.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);
});
我正在 Laravel 使用 Vue.js 制作应用程序。我想在触发方法时等待两秒钟,然后执行存储操作。但是,当我实现这个时,我收到一个错误。
这是我的代码:
.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
内部有问题。有人可以帮我操纵一下吗?
这篇 post 可能会对您有所帮助:
重要的一点:
this
in anonymous function is attached to that anonymous function not to your main function
你可以试试这个:
.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);
});