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

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

但是,我不想在开头本身就加载这些文件。

只有在用户打开特定组件(使用路由器视图)时才需要支付网关。

有办法实现这个目标吗?

谢谢。


当前回答

这可以像这样简单地完成。

  created() {
    var scripts = [
      "https://cloudfront.net/js/jquery-3.4.1.min.js",
      "js/local.js"
    ];
    scripts.forEach(script => {
      let tag = document.createElement("script");
      tag.setAttribute("src", script);
      document.head.appendChild(tag);
    });
  }

其他回答

这个用例有一个vue组件

https://github.com/TheDynomike/vue-script-component#usage

<template>
    <div>
        <VueScriptComponent script='<script type="text/javascript"> alert("Peekaboo!"); </script>'/>
    <div>
</template>

<script>
import VueScriptComponent from 'vue-script-component'

export default {
  ...
  components: {
    ...
    VueScriptComponent
  }
  ...
}
</script>

最简单的解决方案是将脚本添加到vue-project的index.html文件中

index . html:

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <title>vue-webpack</title>
   </head>
   <body>
      <div id="app"></div>
      <!-- start Mixpanel --><script type="text/javascript">(function(c,a){if(!a.__SV){var b=window;try{var d,m,j,k=b.location,f=k.hash;d=function(a,b){return(m=a.match(RegExp(b+"=([^&]*)")))?m[1]:null};f&&d(f,"state")&&(j=JSON.parse(decodeURIComponent(d(f,"state"))),"mpeditor"===j.action&&(b.sessionStorage.setItem("_mpcehash",f),history.replaceState(j.desiredHash||"",c.title,k.pathname+k.search)))}catch(n){}var l,h;window.mixpanel=a;a._i=[];a.init=function(b,d,g){function c(b,i){var a=i.split(".");2==a.length&&(b=b[a[0]],i=a[1]);b[i]=function(){b.push([i].concat(Array.prototype.slice.call(arguments,
         0)))}}var e=a;"undefined"!==typeof g?e=a[g]=[]:g="mixpanel";e.people=e.people||[];e.toString=function(b){var a="mixpanel";"mixpanel"!==g&&(a+="."+g);b||(a+=" (stub)");return a};e.people.toString=function(){return e.toString(1)+".people (stub)"};l="disable time_event track track_pageview track_links track_forms track_with_groups add_group set_group remove_group register register_once alias unregister identify name_tag set_config reset opt_in_tracking opt_out_tracking has_opted_in_tracking has_opted_out_tracking clear_opt_in_out_tracking people.set people.set_once people.unset people.increment people.append people.union people.track_charge people.clear_charges people.delete_user people.remove".split(" ");
         for(h=0;h<l.length;h++)c(e,l[h]);var f="set set_once union unset remove delete".split(" ");e.get_group=function(){function a(c){b[c]=function(){call2_args=arguments;call2=[c].concat(Array.prototype.slice.call(call2_args,0));e.push([d,call2])}}for(var b={},d=["get_group"].concat(Array.prototype.slice.call(arguments,0)),c=0;c<f.length;c++)a(f[c]);return b};a._i.push([b,d,g])};a.__SV=1.2;b=c.createElement("script");b.type="text/javascript";b.async=!0;b.src="undefined"!==typeof MIXPANEL_CUSTOM_LIB_URL?
         MIXPANEL_CUSTOM_LIB_URL:"file:"===c.location.protocol&&"//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js".match(/^\/\//)?"https://cdn.mxpnl.com/libs/mixpanel-2-latest.min.js":"//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js";d=c.getElementsByTagName("script")[0];d.parentNode.insertBefore(b,d)}})(document,window.mixpanel||[]);
         mixpanel.init("xyz");
      </script><!-- end Mixpanel -->
      <script src="/dist/build.js"></script>
   </body>
</html>

您是否正在使用vue的Webpack入门模板(https://github.com/vuejs-templates/webpack)?vue-loader (https://github.com/vuejs/vue-loader)已经设置好了。如果你不使用启动器模板,你必须设置webpack和vue-loader。

然后,您可以将脚本导入到相关的(单个文件)组件。在此之前,你必须从脚本中导出你想导入到组件中的内容。

ES6进口: ——https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import ——http://exploringjs.com/es6/ch_modules.html

~编辑~ 你可以从这些包装器中导入: ——https://github.com/matfish2/vue-stripe ——https://github.com/khoanguyen96/vue-paypal-checkout

好吧,这是我在qiokian(一个live2d动画人物vuejs组件)中的实践:

(以下来自src/qiokian.vue文件)

<script>
export default {
    data() {
        return {
            live2d_path:
                'https://cdn.jsdelivr.net/gh/knowscount/live2d-widget@latest/',
            cdnPath: 'https://cdn.jsdelivr.net/gh/fghrsh/live2d_api/',
        }
    },
<!-- ... -->
        loadAssets() {
            // load waifu.css live2d.min.js waifu-tips.js
            if (screen.width >= 768) {
                Promise.all([
                    this.loadExternalResource(
                        this.live2d_path + 'waifu.css',
                        'css'
                    ),
<!-- ... -->
        loadExternalResource(url, type) {
            // note: live2d_path parameter should be an absolute path
            // const live2d_path =
            //   "https://cdn.jsdelivr.net/gh/knowscount/live2d-widget@latest/";
            //const live2d_path = "/live2d-widget/";
            return new Promise((resolve, reject) => {
                let tag

                if (type === 'css') {
                    tag = document.createElement('link')
                    tag.rel = 'stylesheet'
                    tag.href = url
                } else if (type === 'js') {
                    tag = document.createElement('script')
                    tag.src = url
                }
                if (tag) {
                    tag.onload = () => resolve(url)
                    tag.onerror = () => reject(url)
                    document.head.appendChild(tag)
                }
            })
        },
    },
}

如果你试图利用一个在JavaScript文件中定义的变量,而这个文件是异步加载的,你收到一个'undefined'错误,这很可能是因为脚本还没有完成加载。要解决这个问题,可以利用onload函数确保脚本在尝试访问变量之前已经完成加载。举个例子:

const script = document.createElement(...) // set attribute and so on...
script.onload = () => {
  // do something with some variables/functions/logic from the loaded script
}