我将 stripe 与 VueJS 一起使用,以便在不刷新页面的情况下提交表单,我有 stripe 功能,因此这不一定与 Stripe 相关。
这些方法位于同一组件内。
填写表单后,将调用此方法来创建卡 token (异步函数)
tokenize : function(){
console.log("tokenizing");
this.stripe.createToken(this.card.number).then(function(result) {
console.log(result);
if (result.error) {
// Inform the customer that there was an error.
var errorElement = document.getElementById('card-errors');
errorElement.textContent = result.error.message;
console.log(result.error.message);
} else {
this.token = result.token.id; // the token i need
console.log(this.token); // token gets printed out in log
this.submit(); // <<<<<<<<< THIS IS THE METHOD NOT BEING CALLED
}
});
},
这是提交函数,根本没有被调用。
submit : function(){
console.log(this.token); // <<<<<<< NOTHING GETS PRINTED, DOESN"T ENTER THIS METHOD AT ALL
console.log("here, token added");
if(!document.getElementById('agreement').checked){
this.$root.notify("You must agree to the terms.","danger");
return;
}
console.log("about to send body");
var body = {
_token : this.$root.csrf,
_method : "PUT",
stripeToken : token,
name : this.name,
agreement : true,
};
console.log(body);
console.log("pre axios");
axios.put((window.location.origin + "/billing/" + this.$root.user.company_id),body).then(response => {
this.my_billing = response.data;
this.$root.notify("Card has been successfully added!","success");
this.bEditMode = false;
}).catch(error => {
this.$root.notify("Failed to add new card.","danger");
});
},
我还尝试将输入标记设置为此 token 的值,然后在输入标记上添加 @change
,但是当输入标记的值时也不会调用变化。
我还尝试使我的 this.token
成为具有 setter 和 getter 的计算属性,基本上在设置 token 时调用 this.submit
。这也行不通。
为什么这个方法没有被调用?我之前在异步回调中调用过函数,但是我缺少什么吗?更好的是,还有其他可能的解决方案可以解决这个问题吗?
最佳答案
您需要将“this”绑定(bind)到您的函数。
this.stripe.createToken(this.card.number).then(function(result) {
....
}.bind(this));
这应该可以解决您的问题。 如果没有bind(this),this.token也只能在您的函数中使用,而不能在您的数据属性中设置。
关于javascript - 异步函数回调时未调用 VueJS 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54846476/