【问题标题】:VueJS: Convert normal JS to vueJs and with refVueJS:将普通 JS 转换为 vueJs 并使用 ref
【发布时间】:2021-03-11 14:40:41
【问题描述】:

我在普通 JS 中有以下代码,我想将其转换为 vuejs。

HTML:

<div id="ndi"></div>

JS:

const initAuthSessionResponse = window.NDI.initAuthSession(
        "ndi",
        {
          clientId: "abcd1234", // Replace with your client ID
          redirectUri: "https://primuslogin.firebaseapp.com/callback/", // Replace with a registered redirect URI
          scope: "openid",
          responseType: "code"
        },
        authParamsSupplier,
        onError
      );

在 vuejs 中我是这样做的,但不知何故它不起作用。

<div ref="ndi"></div>

  window.NDI.initAuthSession(
    this.$refs.ndi,
    {
      clientId: "abcd1234", // Replace with your client ID
      redirectUri: "https://primuslogin.firebaseapp.com/callback/", // Replace with a registered redirect URI
      scope: "openid",
      responseType: "code"
    },
    { state: "abc", nonce: "def" },
    this.onError
  );

我想知道如何将 div 中的 id 转换为通常使用 ref 完成的 vuejs 样式。任何帮助将不胜感激。

这是整个 vuejs 版本: https://gist.github.com/somaria/e965264060502a3c1554953487c7dcff

这是正常的js版本: https://gist.github.com/somaria/e965264060502a3c1554953487c7dcff

普通的 js 版本运行良好,但我想将其转换为 vuejs。

【问题讨论】:

    标签: javascript vue.js nuxtjs


    【解决方案1】:

    根据我对window.NDI.initAuthSession 的实验,似乎第一个参数必须 是元素ID。它不接受元素实例,所以你不能在这里使用 Vue 的模板引用。

    我看到的唯一解决方案是将 ID 应用于组件中的元素,就像您在原始标记中所做的那样。

    如果您打算在页面上同时拥有 Vue 组件的多个实例,则需要唯一的 ID,以便元素查找可以选择正确的实例。您可以生成一个唯一的 ID,如下所示:

    <template>
      <div :id="uniqueId"></div>
    </template>
    
    <script>
    let nextId = 0
    const generateId = () => `ndi-${nextId++}`
    
    export default {
      async mounted() {
        this.uniqueId = generateId()
        // wait $nextTick for id binding to take effect
        await this.$nextTick()
    
        window.NDI.initAuthSession(this.uniqueId, ...)
      }
    }
    </script>
    

    另外,我注意到您在注入 NDI 脚本后等待了 3 秒钟,然后才使用window.NDI。脚本加载后使用window.NDI 是安全的,因此您可以添加load-事件监听器(或设置onload):

    const embeddedScript = document.createElement('script')
    embeddedScript.src = '...'
    embeddedScript.onload = () => window.NDI.initAuthSession(...)
    

    demo

    【讨论】:

      猜你喜欢
      • 2019-11-19
      • 2021-02-11
      • 2020-09-23
      • 2018-08-18
      • 2018-12-24
      • 1970-01-01
      • 2018-03-17
      • 2021-07-16
      • 1970-01-01
      相关资源
      最近更新 更多