Jefferson Bruchado
Jefferson Bruchado

Reputation: 908

Insert a script tag inside template Vue

I'm creating a integration with a payment service. The payment service provides me a form with a script tag inside, I want to insert that form with script tag inside my component template, but vue doesn't allow the insertion of tag script within a template, how can I insert that form with script tag inside my template component?

the form with checkout of 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 expected result: 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>

Upvotes: 8

Views: 11314

Answers (2)

Sulivan
Sulivan

Reputation: 11

I know this is a bit old but I came across with this problem with MercadoPago and TommyF's answer really solved it. But in my case the data-transaction-amount needed to be updated dynamically depending on users choices... So if anyone facing this, my workaround was to put it inside updated(), set an id to script tag and verify if id exists. Existing, I remove by id and all .mercadopago-button. PS: I'm newbie on JS and Vue.

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

Upvotes: 1

TommyF
TommyF

Reputation: 7150

You can use an element reference and vanilla JS to add the relevant tag to the dom.

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

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

Upvotes: 10

Related Questions