How to use external JavaScript objects in Vue.js methods

。_饼干妹妹 提交于 2019-12-11 05:35:15

问题


I'm trying to get Stripe working with my Vue.js 2 application. For PCI-DSS reasons, Stripe requires that their Javascript is always loaded from js.stripe.com. I've followed the instructions in:

  • How to add external JS scripts to VueJS Components
  • How to include a CDN to VueJS CLI without NPM or Webpack?

but I get a 'Stripe' is not defined error when I try to use the library. These solutions seemed to be aimed at merely getting a <script> tag into the output HTML (e.g. for analytics), not actually consuming the functions and objects in that script.

Here's what my component Javascript looks like:

<script>
    export default {
        name: "PaymentPage",
        mounted() {
            let stripeScript = document.createElement('script');
            stripeScript.setAttribute('src', 'https://js.stripe.com/v3/');
            document.head.appendChild(stripeScript);

            let s = Stripe('pk_test_Fooo');
            console.log(s);
        }
    }
</script>

I also tried adding the script tag to my public/index.html file instead, but I get the same outcome. This would probably be my preferred route, since Stripe encourages developers to import their script on all pages on the site.

<!DOCTYPE html>
<html lang="en">
  <head>
    // ...
    <script src="https://js.stripe.com/v3/"></script>
  </head>

How can I pull a script from an external CDN and use it within my component's Javascript?

I'm aware of some libraries to integrate Vue.js with Stripe (e.g. matfish2/vue-stripe and jofftiquez/vue-stripe-checkout), but the former doesn't import properly for me (I'm hitting issue #24) and the latter is built against the older Stripe API and the new version is still in beta.


回答1:


You aren't giving the script time to load before checking if Stripe is there. What you need is something like this:

<script>
    export default {
        name: "PaymentPage",
        mounted() {
            let stripeScript = document.createElement('script');
            stripeScript.setAttribute('src', 'https://js.stripe.com/v3/');
            stripeScript.onload = () => {
              let s = Stripe('pk_test_Fooo');
              console.log(s);
            };

            document.head.appendChild(stripeScript);
        }
    }
</script>



回答2:


Thanks to yuriy636's comment, I realised that errors were only from the linter, which presumably can't statically figure out what I'm up to.

I opted to put the script into index.html, then ensured I squashed linter errors with:

// eslint-disable-next-line no-undef
let s = Stripe('pk_test_Fooo');


来源:https://stackoverflow.com/questions/57840349/how-to-use-external-javascript-objects-in-vue-js-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!