动态加载验证码脚本 vue



我想动态加载脚本,例如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.

我该如何解决此问题?

在你的登录 Vue 页面,添加:

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()
}

最新更新