Utilizing external JavaScript objects within Vue.js methods

I am currently working on integrating Stripe with my Vue.js 2 application. To comply with PCI-DSS requirements, Stripe mandates that their Javascript must always be loaded from js.stripe.com. I have followed the guidelines provided in:

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

However, upon implementation, I encounter an error stating 'Stripe' is not defined when trying to use the library. It seems like these solutions are focused on merely inserting a <script> tag into the output HTML (e.g., for analytics) rather than actually utilizing the functions and objects within that script.

This is how my component's JavaScript code looks:

<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>

Even attempting to insert the script tag into my public/index.html file results in the same issue. Ideally, this would be my preferred method as Stripe recommends 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>

Is there a way to fetch a script from an external CDN and effectively incorporate it into my component's JavaScript?

Although I am aware of some libraries that facilitate the integration of Vue.js with Stripe (such as matfish2/vue-stripe and jofftiquez/vue-stripe-checkout), I have encountered difficulties with them - matfish2/vue-stripe does not import correctly due to issue #24, while jofftiquez/vue-stripe-checkout is designed for the older Stripe API, with the new version still in beta.

Answer №1

Before checking if Stripe is available, ensure the script has enough time to load. Adjust your code to look 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>

Answer №2

After reading a helpful comment from yuriy636, I came to the realization that the errors I was encountering were related to the linter and its inability to fully understand my code.

To address this issue, I made the decision to move the script to my index.html file and effectively removed any linter errors by including the following line:

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

Answer №3

When I encountered issues calling functions from a specific script, I found that specifying the ¨window¨ scope was necessary. Additionally, when needing to access Vue elements within the ¨onload¨ function, creating a new variable for the ¨this¨ instance proved to be helpful.

<script>
export default {
    name: "PaymentPage",
    mounted() {
        let stripeScript = document.createElement('script');
        // Creating a new variable for Vue elements.
        let self = this;

        stripeScript.onload = () => {
          // Calling a script function using the 'window' scope.
          window.Stripe('pk_test_Fooo');
          // Accessing other Vue elements
          self.otherVueMethod();
          
        };
        stripeScript.setAttribute('src', 'https://js.stripe.com/v3/');
        document.head.appendChild(stripeScript);
    }
}

I implemented this solution while working with Vue 2.6.

Answer №4

To start using the features of Stripe, all you need to do is install the npm package with this command: npm install @stripe/stripe-js. After that, you can simply import it like any other library.

import { loadStripe } from "@stripe/stripe-js";

export default {
  async mounted() {
    // Initialize stripe
    const stripe = await loadStripe('your_stripe_key_here');
    this.stripe = stripe; // Save the instance of stripe for later use
    // You can now access the stripe instance in your methods or wherever needed
  },
}

This information was confirmed as accurate on January 6th, 2022.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize the passed value within the $scope.$on function

When I use broadcast to send data, I encounter an issue. Here is the code snippet: $rootScope.$broadcast('myEvent',{ data:"value" }); Now, here is my 'on' code: $scope.$on('myEvent', (event, args) => { $scope.da ...

What is the best way to open just a single detail in a b-table?

When the button is clicked, the row details are opened. To ensure that only one line detail remains open at a time, I want any previously open details to be closed when another one is opened. view sample screenshot If you look at the example provided, mu ...

The pop-up menu is obstructed by the dialog box

Within my dialog, there is a gridview that allows the user to input information. One of the textboxes within the grid has a button adjacent to it. Upon clicking this button, a menu appears with a selection of items for the user to choose from, and the sele ...

Can wildcard paths be imported in React using Typescript?

Is there a way to dynamically import a React Typescript Component from a wildcard path, similar to the following code snippet? const Component = loadable( () => import(`../../../src/**/*/${component_name}`), ); I have searched numerous solutions on ...

Can you explain the distinction between using router.METHOD() versus router.route() in Express?

There are two different ways I've come across of writing this code. router.get(path, callback) and router.route(path).get(callback) Based on the surrounding code, they seem to have the same functionality. The documentation for these methods can be ...

What is the best way to retrieve ViewBag data using jQuery?

Greetings, I am currently in the process of developing a web application using MVC5. Within this application, I have implemented a login form that consists of fields for both username and password: @using (Html.BeginForm("ClickAction", "Login", FormMethod ...

Learn how to send data from a MySQL server to a Node.js application using Socket.IO

I've been facing a challenge recently. I am attempting to listen for events from the @rodrigogs/my-sql events node package and then emit those events through socket-io to the react client. However, there seems to be a disconnect that I can't see ...

Having trouble choosing an option from the dropdown menu in bootstrap

I'm experiencing an issue with a bootstrap dropdown that I created. I am unable to select an item from it. The code is shown below: var aos = ''; $('.dropdown-item').click(function(event) { event.preventDefault(); // Prevents ...

Prevent identical values from being added repeatedly to a table while updating in real-time

Currently, I am facing an issue while running through a loop to extract values from an array. When I add a second value, it duplicates both the new and previous values in the table. For example, adding a row with value 488 works fine: <tr class="exe"& ...

The scrolling experience in Next js is not as smooth as expected due to laggy MOMENTUM

Currently, I am in the process of constructing my portfolio website using Next.js with Typescript. Although I am relatively new to both Next.js and Typescript, I decided to leverage them as a learning opportunity. Interestingly, I encountered an issue with ...

Implementing long-lasting login functionality in React using JSON Web Tokens

Currently, I have developed an application using React client/Express API with functioning Authentication. Users are able to register and login successfully. My next step is to implement persistent login using JWT tokens so that when a user accesses the U ...

How can jQuery be referenced?

Is there a way to adjust the jQuery code that targets the elements above within the HTML? The HTML code looks like this: <div class="dramer"> <ul> <li> </li> <li> <a class="shares" href="#"> Click & ...

Angular JS Array with N-level hierarchy

I am developing an application for questionnaires, where questions have responses that can lead to child questions with even more responses. This creates a hierarchical structure of multiple levels. I am looking for the best strategy to display this data i ...

Navigating the AngularJS Directive Controller

I am encountering difficulties while trying to access my controller within a directive that I am attempting to unit test using jasmine and karma testrunner. The structure of the directive is as follows: directive angular.module('Common.accountSearch ...

Enhance the "content switcher" code

I have been working on improving my "contenthandler" function. It currently changes different articles when I click different buttons, which I am satisfied with. However, I believe there may be a better approach to this and would appreciate any advice on h ...

Utilizing both react useState and useLoaderData simultaneously can lead to an infinite loop error

Situation at hand: I am facing a scenario where I have an element called "root" that checks for user authentication every time it is invoked. As I explore the new React-Router V6, I encountered something known as "loaders". When I make an API call through ...

Echo input and refresh on the current page upon submission

I am facing an issue with refreshing the page after submitting a form. I want to refresh the page so that the login attempt can be counted, but currently, the form is displayed without the page being refreshed to add to the count. This is my current code s ...

The try/catch block proves ineffective at handling a socket connection exception

I am attempting to test connection to a non-existent socket. In this scenario, an exception is thrown and I anticipate it being caught in the try/catch block below. The function createConnection is imported from the net package. try { createConnection( ...

Tips for accessing QInput element after mounting in Quasar 2

I need to access the QInput element as soon as it is mounted, so I decided to create a custom directive. However, when I checked the console, the element that was being displayed was QLabel instead of QInput. How can I properly access the QInput element ...

There was an error trying to read properties of undefined, specifically the 'prototype', in a code using Next.Js and Express

While attempting to incorporate express into my next.js project, I encountered errors when trying to initialize express: const express = require('express'); The errors that appeared were: Module not found: Can't resolve 'async_hooks ...