Tim Liberty
Tim Liberty

Reputation: 2149

Load recaptcha script dynamically vue

I want to dynamically load the script such as recaptcha because I only want to load inside Register.Vue / login.Vue component

<script src="https://www.google.com/recaptcha/api.js?onload=vueRecaptchaApiLoaded&render=explicit" async defer>
</script>

If I place the script tag inside my Vue files I get this error:

  - Templates should only be responsible for mapping the state to the UI. Avoid
placing tags with side-effects in your templates, such as <script>, as they will
 not be parsed.

How do I potentially fix this problem?

Upvotes: 1

Views: 2919

Answers (1)

pirs
pirs

Reputation: 2463

In your login Vue page, add :

methods: {

  // create 
  createRecaptcha () {
    let script = document.createElement('script')
    script.setAttribute('async', '')
    script.setAttribute('defer', '')
    script.id = 'recaptchaScript'
    script.src = 'https://www.google.com/recaptcha/api.js?onload=vueRecaptchaApiLoaded&render=explicit'
    script.onload = function () {
      document.getElementsByTagName('head')[0].appendChild(script)
    }
  },
  
  // remove
  removeRecaptcha () {
    document.getElementById('recaptchaScript').remove()
  }

},

// your code ...

mounted () {
  this.createRecaptcha()
},

beforeDestroy () {
  this.removeRecaptcha()
}

Upvotes: 4

Related Questions