导入 javascript 文件以在 vue 组件中使用 [英] Importing javascript file for use within vue component

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

问题描述

我正在开发一个需要使用 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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆