[javascript] VueJS 구성 요소에 외부 JS 스크립트를 추가하는 방법

지불 게이트웨이에 두 개의 외부 스크립트를 사용해야합니다. 지금은 둘 다 index.html파일에 저장됩니다. 그러나 처음에는 이러한 파일을로드하고 싶지 않습니다. 결제 게이트웨이는 사용자가 특정 구성 요소를 열 때에 만 필요합니다 ( using router-view).

어쨌든 이것을 달성 할 수 있습니까?



답변

이를 해결하는 간단하고 효과적인 방법은 외부 스크립트를 mounted()구성 요소 의 뷰에 추가하는 것 입니다. 나는 당신을 설명 할 것이다 구글에서 reCAPTCHA의 스크립트 :

<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 파일 및 jquery와 함께 제공되는 HTML 템플릿을 다운로드했습니다. 그 js를 내 앱에 연결해야했습니다. Vue를 계속하십시오.

이 플러그인을 발견하면 CDN과 정적 파일 모두에서 외부 스크립트를 추가하는 깔끔한 방법입니다
https://www.npmjs.com/package/vue-plugin-load-script

// local files
// you have to put your scripts into the public folder. 
// that way webpack simply copy these files as it is.
Vue.loadScript("/js/jquery-2.2.4.min.js")

// cdn
Vue.loadScript("https://maps.googleapis.com/maps/api/js")


답변

webpack과 vue loader를 사용하면 다음과 같이 할 수 있습니다

구성 요소를 만들기 전에 외부 스크립트가로드 될 때까지 기다리므로 구성 요소에서 globar vars 등을 사용할 수 있습니다

components: {
 SomeComponent: () => {
  return new Promise((resolve, reject) => {
   let script = document.createElement('script')
   script.onload = () => {
    resolve(import(someComponent))
   }
   script.async = true
   script.src = 'https://maps.googleapis.com/maps/api/js?key=APIKEY&libraries=places'
   document.head.appendChild(script)
  })
 }
},


답변

vue ( https://github.com/vuejs-templates/webpack ) 용 Webpack 시작 템플릿 중 하나를 사용하고 있습니까? 이미 vue-loader ( https://github.com/vuejs/vue-loader )로 설정되어 있습니다. 스타터 템플릿을 사용하지 않는 경우 webpack 및 vue-loader를 설정해야합니다.

그런 import다음 스크립트를 관련 (단일 파일) 구성 요소 로 보낼 수 있습니다 . 그 전에는 export스크립트에서 import구성 요소에 원하는 것을 가져와야합니다.

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


답변

뷰 헤드를 사용할 수 있습니다 패키지를 스크립트 및 기타 태그를 vue 구성 요소의 헤드에 추가 .

다음과 같이 간단합니다.

var myComponent = Vue.extend({
  data: function () {
    return {
      ...
    }
  },
  head: {
    title: {
      inner: 'It will be a pleasure'
    },
    // Meta tags
    meta: [
      { name: 'application-name', content: 'Name of my application' },
      { name: 'description', content: 'A description of the page', id: 'desc' }, // id to replace intead of create element
      // ...
      // Twitter
      { name: 'twitter:title', content: 'Content Title' },
      // with shorthand
      { n: 'twitter:description', c: 'Content description less than 200 characters'},
      // ...
      // Google+ / Schema.org
      { itemprop: 'name', content: 'Content Title' },
      { itemprop: 'description', content: 'Content Title' },
      // ...
      // Facebook / Open Graph
      { property: 'fb:app_id', content: '123456789' },
      { property: 'og:title', content: 'Content Title' },
      // with shorthand
      { p: 'og:image', c: 'https://example.com/image.jpg' },
      // ...
    ],
    // link tags
    link: [
      { rel: 'canonical', href: 'http://example.com/#!/contact/', id: 'canonical' },
      { rel: 'author', href: 'author', undo: false }, // undo property - not to remove the element
      { rel: 'icon', href: require('./path/to/icon-16.png'), sizes: '16x16', type: 'image/png' },
      // with shorthand
      { r: 'icon', h: 'path/to/icon-32.png', sz: '32x32', t: 'image/png' },
      // ...
    ],
    script: [
      { type: 'text/javascript', src: 'cdn/to/script.js', async: true, body: true}, // Insert in body
      // with shorthand
      { t: 'application/ld+json', i: '{ "@context": "http://schema.org" }' },
      // ...
    ],
    style: [
      { type: 'text/css', inner: 'body { background-color: #000; color: #fff}', undo: false },
      // ...
    ]
  }
})

더 많은 예제를 보려면 이 링크 를 확인하십시오 .


답변

외부 js 스크립트를 vue.js 컴포넌트 템플리트에 임베드하려는 경우 다음을 수행하십시오.

다음 과 같이 외부 자바 스크립트 포함 코드 를 구성 요소 에 추가하고 싶었습니다 .

<template>
  <div>
    This is my component
    <script src="https://badge.dimensions.ai/badge.js"></script>
  </div>
<template>

그리고 Vue는 나 에게이 오류를 보여주었습니다.

템플릿은 상태를 UI에 매핑하는 역할 만합니다. 템플릿에 부작용이있는 태그는 구문 분석되지 않으므로 태그에 배치하지 마십시오.


내가 해결 한 방법은 다음을 추가하는 것입니다type="application/javascript" ( js MIME 유형에 대해 자세히 알아 보려면이 질문을 참조하십시오 ).

<script type="application/javascript" defer src="..."></script>


defer속성을 알 수 있습니다 . Kyle이 더 많은 비디오를 보고 싶다면


답변

약속 기반 솔루션으로 필요한 스크립트를로드 할 수 있습니다.

export default {
  data () {
    return { is_script_loading: false }
  },
  created () {
    // If another component is already loading the script
    this.$root.$on('loading_script', e => { this.is_script_loading = true })
  },
  methods: {
    load_script () {
      let self = this
      return new Promise((resolve, reject) => {

        // if script is already loading via another component
        if ( self.is_script_loading ){
          // Resolve when the other component has loaded the script
          this.$root.$on('script_loaded', resolve)
          return
        }

        let script = document.createElement('script')
        script.setAttribute('src', 'https://www.google.com/recaptcha/api.js')
        script.async = true

        this.$root.$emit('loading_script')

        script.onload = () => {
          /* emit to global event bus to inform other components
           * we are already loading the script */
          this.$root.$emit('script_loaded')
          resolve()
        }

        document.head.appendChild(script)

      })

    },

    async use_script () {
      try {
        await this.load_script()
        // .. do what you want after script has loaded
      } catch (err) { console.log(err) }

    }
  }
}

참고하시기 바랍니다 this.$root약간의 해키 당신은 사용해야 vuex 또는 eventHub의 대신 글로벌 이벤트에 대한 솔루션을.

위의 구성 요소를 만들어 필요할 때마다 사용하면 스크립트를 사용할 때만로드됩니다.