0

I use vue-js and stripe to implement some of my payment.

The only way to use the Stripe with vue-js was with script.onload. I would like now to access some of my methods within the onload function. In this example it is the function myMethod called with self.myMethod

To do so I created self variable but it happens to be undefined in the scope of onload.

How could I do to make it available ?

In the current example self refers to Window object.

Component.vue

<template></template>

<script>
export default {
     data() {
         const self = this;
         return {}
     },

     methods: {
         myMethod() {}
     },

     mounted() {
         let script = document.createElement('script');
         script.src = "https://js.stripe.com/v3/";
         script.onload = () => {
             const stripe = Stripe('xxxxxxxx');
             const elements = stripe.elements();

             function setOutcome(result) {
                 self.myMethod();
             }
             card.on('change', function(event) {
                 setOutcome(event);
             });
             document.querySelector('form').addEventListener('submit', function(e) {
                 e.preventDefault();
                 const form = document.querySelector('form');
                 stripe.createToken(card).then(setOutcome);
             });
         };
         document.body.appendChild(script);
     }
 }
</script>
<style></style>
0

1 Answer 1

1

You've defined a self variable in the data method, which is inaccessible outside of that method.

You need to define the self variable within the mounted hook itself:

mounted() {
  let self = this;
  ...
}
Sign up to request clarification or add additional context in comments.

7 Comments

By doing like you said, self still refers to window and I don't know how to access my method.
It shouldn't refer to window if the exported object is being used in the instantiation of a Vue component. Can you show the code where you are importing this file and using it? Or is this within a .vue file?
This is a component component.vue. Sorry I forgot to mention that and I updated the description.
But you have <script> tags around your export default {} object right?
Argh ... Yes, I am sorry again. I'm using Single File component. The self reference changes when I am in script.onload = ()
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.