Importing javascript file for use within vue component Importing javascript file for use within vue component vue.js vue.js

Importing javascript file for use within vue component


Include an external JavaScript file

Try including your (external) JavaScript into the mounted hook of your Vue component.

<script>export default {  mounted() {    const plugin = document.createElement("script");    plugin.setAttribute(      "src",      "//api.myplugincom/widget/mykey.js"    );    plugin.async = true;    document.head.appendChild(plugin);  }};</script>

Reference: How to include a tag on a Vue component

Import a local JavaScript file

In the case that you would like to import a local JavaScript in your Vue component, you can import it this way:

MyComponent.vue

<script>import * as mykey from '../assets/js/mykey.js'export default {  data() {    return {      message: `Hello ${mykey.MY_CONST}!` // Hello Vue.js!    }  }}</script>

Suppose your project structure looks like:

src- assets    - js      - mykey.js- components    MyComponent.vue

And you can export variables or functions in mykey.js:

export let myVariable = {};export const MY_CONST = 'Vue.js';export function myFoo(a, b) {    return a + b;}

Note: checked with Vue.js version 2.6.10


try to download this script
import * from '{path}/mykey.js'.
or import script
<script src="//api.myplugincom/widget/mykey.js"></script>in <head>, use global variable in your component.


For scripts you bring in the browser way (i.e., with tags), they generally make some variable available globally.

For these, you don't have to import anything. They'll just be available.

If you are using something like Webstorm (or any of the related JetBrains IDEs), you can add /* global globalValueHere */ to let it know that "hey, this isn't defined in my file, but it exists." It isn't required, but it'll make the "undefined" squiggly lines go away.

For example:

/* global Vue */

is what I use when I am pulling Vue down from a CDN (instead of using it directly).

Beyond that, you just use it as you normally would.