【问题标题】:Load recaptcha script dynamically vue动态加载recaptcha脚本vue
【发布时间】:2017-11-10 05:27:24
【问题描述】:

我想动态加载诸如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.

我该如何解决这个问题?

【问题讨论】:

    标签: javascript vue.js vuejs2


    【解决方案1】:

    在你的登录 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()
    }
    

    【讨论】:

    • 谢谢 当我导航回组件时,这不会继续添加重复的脚本吗?可以检查一下这个脚本是否存在吗?
    猜你喜欢
    • 1970-01-01
    • 2014-03-10
    • 1970-01-01
    • 2010-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多