且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在VueJS组件中添加外部JS脚本?

更新时间:2023-11-02 11:38:52

一种简单有效的解决方案,它是通过将外部脚本添加到组件的vue Mounted()中来实现的.我将用 Google Recaptcha 脚本向您说明:

A simple and effective way to solve this, it's by adding your external script into the vue mounted() of your component. I will illustrate you with the Google Recaptcha script:

<template>
   .... your HTML
</template>

<script>
  export default {
    data: () => ({
      ......data of your component
    }),
    mounted() {
      let recaptchaScript = document.createElement('script')
      recaptchaScript.setAttribute('src', 'https://www.google.com/recaptcha/api.js')
      document.head.appendChild(recaptchaScript)
    },
    methods: {
      ......methods of your component
    }
  }
</script>

来源: https://medium.com/@lassiuosukainen/how-to-include-a-script-tag-on-a-vue-component-fe10940af9e8