How to add external JS scripts to VueJS Components

2019-01-06 13:12发布

I've to use two external scripts for the payment gateways. Right now both are put in the 'index.html' file. However, I don't want to load these files at the beginning itself. The payment gateway is needed only in when user open a specific component (using router-view). Is there anyway to achieve this?

6条回答
Emotional °昔
2楼-- · 2019-01-06 13:41

I have downloaded some HTML template that comes with custom js files and jquery. I had to attach those js to my app. and continue with Vue.

Found this plugin, it's a clean way to add external scripts both via CDN and from static files 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")
查看更多
Explosion°爆炸
3楼-- · 2019-01-06 13:44

Are you using one of the Webpack starter templates for vue (https://github.com/vuejs-templates/webpack)? It already comes set up with vue-loader (https://github.com/vuejs/vue-loader). If you're not using a starter template, you have to set up webpack and vue-loader.

You can then import your scripts to the relevant (single file) components. Before that, you have toexport from your scripts what you want to import to your components.

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

~Edit~
You can import from these wrappers:
- https://github.com/matfish2/vue-stripe
- https://github.com/khoanguyen96/vue-paypal-checkout

查看更多
等我变得足够好
4楼-- · 2019-01-06 13:47

A simple and effective way to solve this, it's by adding your external script into the vue mounted() of your component. I will illustrate you with the Google Recaptcha script:

<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>

Source: https://medium.com/@lassiuosukainen/how-to-include-a-script-tag-on-a-vue-component-fe10940af9e8

查看更多
The star\"
5楼-- · 2019-01-06 13:59

using webpack and vue loader you can do something like this

it waits for the external script to load before creating the component, so globar vars etc are available in the component

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)
  })
 }
},
查看更多
趁早两清
6楼-- · 2019-01-06 14:00

You can load the script you need with a promise based solution:

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) }

    }
  }
}

Please note that this.$root is a little hacky and you should use a vuex or eventHub solution for the global events instead.

You would make the above into a component and use it wherever needed, it will only load the script when used.

查看更多
何必那么认真
7楼-- · 2019-01-06 14:03

You can use vue-loader and code your components in their own files (Single file components). This will allow you to include scripts and css on a component basis.

查看更多
登录 后发表回答