动态加载recaptcha脚本vue

时间:2017-11-10 05:27:25

标签: javascript vue.js vuejs2

我想动态加载脚本,例如recaptcha,因为我只想在Register.Vue / login.Vue组件中加载

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

如果我将脚本标记放在我的Vue文件中,我会收到此错误:

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

如何解决此问题?

1 个答案:

答案 0 :(得分:3)

在您的登录Vue页面中,添加:

methods: {
  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)
    }
  }
}

// ...

mounted () {
  createRecaptcha();
},
beforeDestroy () {
  // not tested
  document.getElementById('recaptchaScript').remove()
}