如何将外部 JS 脚本添加到 VueJS 组件? [英] How to add external JS scripts to VueJS Components?

查看:44
本文介绍了如何将外部 JS 脚本添加到 VueJS 组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须为支付网关使用两个外部脚本.

I've to use two external scripts for the payment gateways.

现在两者都放在 index.html 文件中.

Right now both are put in the index.html file.

但是,我不想在一开始就加载这些文件.

However, I don't want to load these files at the beginning itself.

只有在用户打开特定组件时才需要支付网关(using router-view).

The payment gateway is needed only in when user open a specific component (using router-view).

有没有办法做到这一点?

Is there anyway to achieve this?

谢谢.

推荐答案

解决这个问题的一个简单有效的方法,就是将你的外部脚本添加到你组件的 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

这篇关于如何将外部 JS 脚本添加到 VueJS 组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆