导入要在vue组件中使用的javascript

导入要在vue组件中使用的javascript

本文介绍了导入要在vue组件中使用的javascript文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个需要使用js插件的项目中工作.现在,我们正在使用vue,并且我们有一个组件来处理基于插件的逻辑,我需要在vue组件中导入js插件文件,以初始化插件.

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

MyComponent.vue

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

export default {
    data: {

我的问题是,什么是导入此javascript文件的正确方法,以便我可以在vue组件中使用它? ...

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

推荐答案

包括外部JavaScript文件

尝试将您的(外部)JavaScript包含在Vue组件的挂接钩中.

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>

参考:如何在Vue组件上包含标签

如果您想在Vue组件中导入本地JavaScript,则可以通过以下方式导入它:

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

MyComponent.vue

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

您可以在mykey.js中导出变量或函数:

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

注意:已使用Vue.js版本2.6.10

Note: checked with Vue.js version 2.6.10

这篇关于导入要在vue组件中使用的javascript文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 17:09