Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kiwdahc's avatar

Losing this scope while in component method.

I am trying to create a stripe payment form Vuejs2 components. You will see the method I have below. The first console.log(this.stripeEmail); is out putting some data from the vue component and works perfectly in the method. The second one returns "this" as undefined. I think this is because the .then() acts as an arrow function but I am not positive. I need to know how to keep this as the scope of the component so that I can call another method in the else statement. This is beyond my experience in Vuejs2 please help!

    export default {

        data() {

            return {
                stripeEmail : 'asdf',
            }

        },

        methods: {

            createToken() {
                console.log(this.stripeEmail);
                this.stripe.createToken(this.card).then(function(result) {
                    if (result.error) {
                        // Inform the user if there was an error
                        var errorElement = document.getElementById('card-errors');
                        errorElement.textContent = result.error.message;
                    } else {
                        console.log(this.stripeEmail);
                    }
                });
            }

        }
    }
0 likes
2 replies
rawilk's avatar

Try writing the function like this:


           createToken() {
                console.log(this.stripeEmail);
                // Assign 'this' to a local variable
                const vm = this;
                
                this.stripe.createToken(this.card).then(function(result) {
                    if (result.error) {
                        // Inform the user if there was an error
                        var errorElement = document.getElementById('card-errors');
                        errorElement.textContent = result.error.message;
                    } else {
                        // This should show the email now
                        console.log(vm.stripeEmail);
                    }
                });
            }

1 like
jbloomstrom's avatar

You could also use es6 arrow syntax.

createToken() {
    console.log(this.stripeEmail);
    
    this.stripe.createToken(this.card).then( result => {
        if (result.error) {
            // Inform the user if there was an error
            var errorElement = document.getElementById('card-errors');
            errorElement.textContent = result.error.message;
        } else {
            // This should show the email now
            console.log(this.stripeEmail);
        }
    });
}

Please or to participate in this conversation.