Adding external JS scripts to Vue.js Components

We need to use JavaScript in Vue.js for implementing many features like payment gateway, datepicker etc. Normally we put JavaScript in between the body tag of html, head tag of html or in a js file. Mostly we add the JavaScript at the beginning in our index page. This will make the website slow down since the js takes time to load. Lets see how to add js to Vue.js components for example if you want to implement payment gateway and you need the JS only when a user open a specific component. Add your external script into the vue mounted() of the component. This will help to solve the problem.

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