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

The POST function is executed twice, with the first attempt resulting in a failed API call, but the second attempt is

I am experiencing issues with my subscribe dialog, as it seems to be running the API call twice. The first time it fails, but on the second attempt, it succeeds and inserts the email into the database. This double run is causing errors in my AJAX function, ...

The code functions perfectly on my local machine, however it is not cooperating on the HostGator server

A selection box based on values should appear in text fields, The current code is functional in local host but not working on the hostgator server For example, displaying country options based on the selected state and districts based on the selected sta ...

Sending information to a Flask application using AJAX

Currently, I am working on transferring URLs from an extension to a Flask app. The extension is able to access the current URL of the website. I have set up an AJAX request to connect to Flask, and the connection is successful. However, when trying to send ...

Attempting to run the npm install command led to encountering a SyntaxError with an

Recently, I made some alterations to my npm configuration and ever since then, I have been consistently encountering the same error whenever I try to install various packages. It seems that due to a personal mistake in changing the npm settings, I am now u ...

What is the best way to retrieve the value of a dynamically created button in code?

I am dealing with a situation where I have a button that is supposed to fetch some data based on the classroom ID. button(type='button' id='getButton', onclick='get()', value=classroom.id ) Class Students Additionally, I ha ...

Retrieve the visitor's IP address following the submission of an AJAX form

Currently, I am facing an issue with my HTML form and JavaScript method integration. Whenever a visitor submits the form, a JavaScript method is triggered which sends an AJAX request to a PHP file on my server. The problem arises when trying to retrieve ...

What steps can I take to enable search functionality in Ckeditor's richcombo similar to the regular search feature in

I am currently developing a custom dropdown menu using the rich combo feature in CKEDITOR. One of my goals is to include a search functionality within the dropdown, such as a key press search or an input textbox search. This is how my dropdown box appear ...

How can you use jQuery to select and manipulate a wildcard href ID?

There are multiple links listed below: <a href="http://www.google.com" id="link01">Google</a> <a href="http://www.yahoo.com" id="link02">Yahoo</a> <a href="http://www.cnn.com" id="link03">CNN</a> <a href="http://www. ...

What exactly does the term "new.target" refer to?

The ECMAScript 2015 specification references the term new.target a total of three times - once in section 14.2.3: Although Contains typically does not analyze most function forms, it is specifically used to identify new.target, this, and super usage wit ...

Tips for transforming information into JSON format

Imagine having a file with data in CSV or TXT format, such as: Name, Surname, Age, Occupation Gino, DiNanni, 19, Student Anna, Kournikova, 27, Programmer (Extra spaces have been added to enhance readability) The goal ...

Using jQuery to create a blinking effect on a specific letter in a string

I'm looking to create a text adventure using Canvas, and I want the parser to blink continuously, similar to the one in a Dos Console. The parser is stored as a global variable. How can I use jQuery to permanently change the character of this global v ...

I'm curious as to why styled components weren't working before

I'm attempting to utilize the before on styled components in React, but it doesn't seem to be functioning correctly. Prior to adding before, the background image was displayed, but after its inclusion, the image is no longer showing up; import st ...

Extract data from a JSON-encoded array using JavaScript

I sent a JSON encoded array to JavaScript. Now I want to access that array to retrieve the different elements. When I print it out using console.log(), I see this array: array(1) { [16]=> array(2) { [3488]=> array(1) { [0]=> ...

Notify when the button value changes to "submit"

I recently added a jQuery form wizard to my website. I want users to receive an alert in JavaScript when they reach the end of the form. To achieve this, I inserted a simple JavaScript code at the beginning of my page within <head>..some code</hea ...

Issue with AngularJS ui-router failing to resolve a service call

I am facing an issue while trying to implement the resolve feature in my ui-router state provider. Here is how I have configured it: app.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function ($stat ...

Generating npm package without including file extensions in imports

I am currently working on creating an internal library for my workplace. Everything seems to be going smoothly until I try to use it in another project. It appears that the file extension in all of the import statements has disappeared during the npm pack ...

Looking for a way to automatically update a map within a Vue component

My component successfully: Receives a string from a sibling input component via the global Bus method in created() => works Manipulates the string into lat/lng coordinates via geoDecoding() => works Resolves promise result coordinates, sets data, a ...

Looking for the location of a matching brace in a dataset?

As a newbie in the world of coding, I have embarked on learning about NodeJs file system module. Currently, my focus is on handling a large data file stored as a string. The challenge that I am facing is with locating the matching close brace and its pos ...

Choose the right Vue.js component for optimal performance

I have a primary element within which there is a secondary element with vue.js 2.0. The issue arises when the secondary element relies on methods from the primary element. Here's an illustration: Vue.component('primary-element', { tem ...

What is the procedure for adding a URL path in jQuery?

When using $(this).attr("href"); in the jQuery Ajax url field, it correctly retrieves the URL path. However, if I try to use a prefix in front of it like this: $.ajax({ type: 'GET' url: 'api/' + $(this).attr("href"); }) the co ...