How to introduce a third party JS into Vue components

Time:2021-2-15

When using Vue development projects, we often use some good third-party libraries, but there are some libraries that do not provide NPM installation, so we can’t use themimportIt is introduced in a new way. such asvaptchaGesture verification code,vapthcaIt’s a third-party gesture verification code that uses a lot, but the official document can’t be foundnpmHow to install.

Usually when using this kind of third-party library, theindex.htmlIntroduce the SDK provided by the third party library into the file. stayindex.htmlIntroduced invaptchaIt is used globally and will be applied to any component, but it will only be used in the login interface(login.vue)Use tovapthca. althoughvaptchaSmall enough to have little impact on page loading, but please do not introduce it globally.

Use a little trick to achieve on-demand applications, you can create avaptcha.js, add the following code:

export function vaptcha () {
  return new Promise(function (resolve, reject) {
    const tag = document.getElementsByTagName('script')
    for (let i of tag) {
      if (i.src === 'https://v.vaptcha.com/v3.js') {
        resolve(window.vaptcha)
        return
      }
    }
    const script = document.createElement('script')
    script.type = 'text/javascript'
    script.src = 'https://v.vaptcha.com/v3.js'
    script.onerror = reject
    document.body.appendChild(script)
    script.onload = () => {
      resolve(window.vaptcha)
    }
  })
}

And then in thelogin.vueUsed inimportintroduce:

import { vaptcha } from '~/extend/vaptcha'

stayinitVaptchaMethod

initVaptcha () {
  vaptcha().then((vaptcha) => {
    vaptcha({
      Vid: 'XXXX' // verification unit ID
      Type: 'invisible' // display type Click
      Scene: 1, // the default scene value is 0
      offline_ Server: 'xxxxx' // offline mode server address
      Container: '# vaptcha container' // container, which can be element or selector
    }).then((obj) => {
      //
    })
  })
}

In this way, onlylogin.vueLoad invapthca.jsInstead of being introduced globally.


vue

This work adoptsCC agreementReprint must indicate the author and the link of this article