Renato Souza de Oliveira
Renato Souza de Oliveira

Reputation: 4574

How to load external js file in my component VUE 2 (webpack)?

I already looked and I did not find. I have a url from an external js file and I'm importing in my index.html. The file is loading when the application starts.

however, the user will not use the features frequently; And I would like to upload this file only when a specific component was called.

I'm using the vue cli (vue 2) with template webpack.

I've tried something like:

import * as PagSeguroDirectPayment from 'https://stc.sandbox.pagseguro.uol.com.br/pagseguro/api/v2/checkout/pagseguro.directpayment.js';

required('https://stc.sandbox.pagseguro.uol.com.br/pagseguro/api/v2/checkout/pagseguro.directpayment.js');

And they do not working.

need to upload this file to use a payment gateway. can anybody help me?

Upvotes: 3

Views: 2181

Answers (2)

manita pote
manita pote

Reputation: 41

Instead of using it in index.html, create a separate js file and copy the script from the link. Export the required method in js file and import it in the component required.

Upvotes: 1

Daniel
Daniel

Reputation: 35694

This is one of those features that vue has that makes believe that it is really well thought out. To do such a thing is actually super easy.

I'm using this in my routes like this:

// home gets loaded always
const Home = import('@/pages/home')

// profile and account gets loaded on demand
const Profile = () => import('@/pages/profile')
const Account = () => import('@/pages/account')

When used with webpack, this will generate individual files for each component. (01.js, 02.js, etc) These files will load as needed.

Upvotes: 0

Related Questions