Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
940 views
in Technique[技术] by (71.8m points)

import - Importing javascript file for use within vue component

I am working on a project that requires using a js plugin. Now that we're using vue and we have a component to handle the plugin based logic, I need to import the js plugin file within the vue component in order to initialize the plugin.

Previously, this was handled within the markup as follows:

<script src="//api.myplugincom/widget/mykey.js
"></script>

This is what I tried, but I am getting a compile time error:

MyComponent.vue

import Vue from 'vue';
import * from  '//api.myplugincom/widget/mykey.js';

export default {
    data: {

My question is, what is the proper way to import this javascript file so I can use it within my vue component? ...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...