繁体   English   中英

如何在 index.html 的外部脚本中添加额外的动态参数? (Vue.js)

[英]How to add additional dynamic params to the external script in index.html? (Vue.js)

我在 index.html 的 Vuejs 中有一个外部脚本

<script>window.appSettings={app_id:"appId"};</script>

我需要像这样从getters/user传递usernameuserEmail

<script>window.appSettings={app_id:"appId", contact_name: "Alexander the Great",
        contact_email: "alex@empire.com",};</script>

如何正确实现这一目标?

时间将是一个问题。 在 Vue 中,您可以随时写入 window.appSettings。 我建议您在创建或安装的 function 中执行此操作。

一个例子:

{
   mounted() {
      window.appSettings = window.appSettings || {};
      window.appSettings.userId = this.userId;
   }
}

因为外部脚本将使用这些值,所以 Vue 在加载外部脚本之前写入这些值很重要。

为了保证 Vue 先写后加载脚本,最好让 Vue 负责加载外部脚本。 您可以通过动态创建和脚本元素并将其添加到 dom 来做到这一点,如下所示:

{
   mounted() {
      // write the values first
      window.appSettings = window.appSettings || {};
      window.appSettings.userId = this.userId;

      // now load any external scripts:
      var script = document.createElement('script');
      script.src = 'hellozest.io/widget/...';
      document.body.appendChild(script);
   }
}

这种策略可能有效,但正如您所见,Vue 需要了解外部脚本并负责加载它们。 一般来说,我更愿意以不同的方式解决这个问题:

您的应用程序后端是否可以使用 userId 和 userEmail? 然后,您可以在服务器上编写“window.appSettings”,让 Vue 应用程序尽可能简单。

如果只有 Vue 知道 userId 和 userEmail,你可以决定将这个职责隔离在一个 Vue 组件中,因为将这段代码保存在一个地方很重要。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM