javascript - 异步函数回调时未调用 VueJS 方法

标签 javascript asynchronous vue.js

我将 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/

相关文章:

php - POST 操作 SESSION 变量 删除

php - 在图像上标记点

java - Mongodb 异步 java 驱动程序 find()

c# - 等待异步方法而不阻塞线程

javascript - 将数组 Vuejs 中属性的所有值相加

javascript - 如何将 json 放入我的 View 中?

javascript - 设置 vuetify 扩展面板组件的 max-width

android - 在 Android 中下载和暂停、恢复大文件的最佳方式?

javascript - 将 setTimeout 函数分配给 Vue 方法

vue.js - 在 vue3 中通过 props 传递的组件