Place a <script> tag within the Vue template

I am currently developing an integration with a payment service. The payment service has provided me with a form that includes a script tag. I would like to insert this form, including the script tag, into my component template. However, Vue does not allow the direct insertion of a script tag within a template. How can I achieve this and insert the form with script tag into my template component?

Here is the form for checkout from the payment service:

    <form action="http://localhost:8081/api/v1/payment/" method="POST">
      <script
        src="https://www.mercadopago.com.br/integrations/v1/web-tokenize-checkout.js"
        data-public-key="KEY"
        data-transaction-amount="14.90">
      </script>
    </form>

The desired outcome: My component:

<template>
    <div id="dashboard">
        <form action="http://localhost:8081/api/v1/payment/" method="POST">
            <script
                src="https://www.mercadopago.com.br/integrations/v1/web-tokenize-checkout.js"
                data-public-key="KEY"
                data-transaction-amount="14.90">
            </script>
        </form>
    </div>
</template>

<script>
    import { mapState } from "vuex";

    export default {
        data() {
            return {}
        },
    }
</script>

Answer №1

To dynamically add a relevant tag to the dom using vanilla JS, you can utilize an element reference like this:

<form ref="myform">
  ...
</form>

mounted() {
  let newScript = document.createElement('script');    
  newScript.setAttribute("src","https://www.mercadopago.com.br/integrations/v1/web-tokenize-checkout.js");
  newScript.setAttribute("data-transaction-amount", "14.90")
  this.$refs.myform.appendChild(newScript);
}

Answer №2

While this issue may seem dated, I recently encountered a similar problem with MercadoPago and found TommyF's solution to be quite helpful. However, in my scenario, the data-transaction-amount had to be updated dynamically based on user input. To address this, I decided to place it within an updated() function, assign an id to the script tag, and check for the existence of that id. If it exists, I remove it along with all elements with the class .mercadopago-button. Just a note: I'm still new to JavaScript and Vue.js.

let existingScript = document.getElementById('mpScript');
let existingButtons = document.getElementsByClassName('mercadopago-button');
if(existingScript) {
  existingScript.remove();
  while(existingButtons.length > 0) {
    existingButtons[0].parentNode.removeChild(existingButtons[0]);
  }
}

let script = document.createElement('script');
script.setAttribute("src", "https://www.mercadopago.com.br/integrations/v1/web-tokenize-checkout.js");
script.setAttribute("data-transaction-amount", this.total);
script.setAttribute("data-public-key", 'KEY');
script.setAttribute("id", "mpScript");
this.$refs.mpCheckout.appendChild(script);

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

Using AJAX to Send Requests to PHP

Embarking on my first ajax project, I believe I am close to resolving an issue but require some guidance. The webpage file below features an input field where users can enter their email address. Upon submission, the ajax doWork() function should trigger t ...

The difference between emitting and passing functions as props in Vue

Imagine having a versatile button component that is utilized in various other components. Instead of tying the child components to specific functionalities triggered by this button, you want to keep those logics flexible and customizable within each compon ...

What are the best methods for capturing individual and time-sensitive occurrences within a service?

I am currently working on structuring the events within a service to enable a mechanism for subscribing/unsubscribing listeners when a controller's scope is terminated. Previously, I utilized $rootScope.$on in this manner: if(!$rootScope.$$listeners[& ...

Animating the loading of the step bar

Looking for some help with my progress bar created using Vue bootstrap components. I have set a default number in the data with the value: number, and now I want it to increase automatically whenever I navigate to the next page. Can anyone provide some g ...

Managing the AJAX response from a remote CGI script

I'm currently working on a project that involves handling the response of a CGI script located on a remote machine within a PHP generated HTML page on an apache server. The challenge I am facing relates to user authentication and account creation for ...

Encountering an issue when attempting to downgrade React Native version from 0.51 to 0.45

My current project requires me to downgrade due to certain third-party packages not being updated for the latest version of react-native. Specifically, I am using Xcode 9.0. Despite my efforts to downgrade the react-native version, I encountered the follo ...

Firebase web authentication is most effective upon the second attempt

I am currently working on a website that interacts with Google's firebase to read and write data. The website has both anonymous and email authentication enabled. Users can view the data anonymously, but in order to edit or write new data, they must s ...

Explore our array of images displayed in an interactive gallery featuring clickable

I have a query I'm facing an issue with my code. Currently, I have a gallery that displays images perfectly. Now, I want to enhance it by showing a larger resolution of the image when clicked. However, when I add the href tag to link the images, they ...

Save a SQL query as a text file using Node.js

I'm having an issue with my code. I am trying to save the results of a SQL query into a text file, but instead of getting the actual results, all I see in the file is the word "object." const fs = require('fs'); const sql = require('mss ...

Creating a horizontal scroll effect using jQuery when the widths of the items are not

I am working on a jQuery gallery that showcases images in a horizontal layout. Below the images, there are "left" and "right" buttons which allow users to scroll through the pictures. There are many tutorials and plugins available for this type of function ...

The Discord OAuth2 bot fails to assign roles to authenticated users

While working on OAuth2 login for my website, I encountered an issue. After a user successfully logs in through OAuth2, the bot should assign a role to them on my Discord server. However, when I tested the login process myself, the bot returned an error me ...

Flickering observed in AngularJS UI-Router when navigating to a new route

In my AngularJS ui-router setup, I am facing an issue with flickering during state changes while checking the authentication state. When a user is logged in, the URL /#/ is protected and redirects to /#/home. However, there is a brief flicker where the c ...

Is there a way to showcase all the information in products while also organizing it in the same manner that I have?

I am looking to sort prices while displaying all the properties of products at the same time. DATA INPUT: const products = [ { "index": 0, "isSale": true, "isExclusive": false, "price": "Rs.2000", "productImage": "product-1.jpg", ...

JavaScript Array failing to transfer to PHP using AJAX

I've encountered a recurring issue with my code and despite searching for solutions, I can't seem to find one that works for me. The problem lies in trying to delete a specific row from a table based on whether the user selects a checkbox associa ...

The visibility of content that flickers on the webpage should be hidden with the display: none property during loading

Currently working on a new toy website, but encountering some unexpected behavior. On the homepage HTML file, there are two separate sets of <body> tags: <body class = "intro">...</body> <body class = "home">...</body& ...

During the rendering process, the property "projects" was attempted to be accessed, however, it has not been defined within

I am struggling to understand this issue. Despite looking at numerous other problems and solutions, I still can't grasp the root cause of the error. In my projects.js file, there is an array. Whenever I try to import {projects} from "@/projects.js", I ...

Tips for uploading multiple files using django-rest-framework

When trying to upload files using django-rest-frame, I encountered an issue where only the last file uploaded would be saved. How can I ensure that all files are saved? Software versions: Python 3.6.2 Django 2.2.3 djangorestframework 3.10.1 Code snippet: ...

Struggling to get the AJAX code functioning correctly

Embarking on my journey with AJAX, I decided to test a simple example from the Microsoft 70515 book. Surprisingly, the code doesn't seem to be functioning as expected and I'm at a loss trying to figure out why - everything appears to be in order. ...

Text that appears automatically in an input field

I've searched high and low, but I just can't seem to find a solution that works for me. What I need is a way to automatically populate a HTML text field with default text when the page loads. This default text should ideally be a PHP variable and ...

How to Retrieve a Specific Line with jQuery

Could jQuery be used to retrieve the offset of the first letter in the 5th visual line of a block's content? I am referring to the visual line determined by the browser, not the line seen in the source code. ...