在vue组件中使用普通的javascript文件?

xet*_*a11 3 vue.js

我有一个名为的文件Helper.js,其中包含使用某些库的函数。现在我有一个TestComponent.vue文件并想使用这个辅助函数。我怎样才能注入这个功能?

我尝试使用直接在 Components 块中使用的库Helper.js,但似乎 vue 在包含任何库之前运行,无论 index.html 标签的顺序如何。

如何使用 .js 文件或其他库

aBi*_*uit 5

为了在 Vue 模板中使用其他库或辅助函数,您只需将它们导入到模板的脚本标签中即可:

TestComponent.vue

<template>
<!-- template markup -->
</template>

<script>
import Helper from 'relative/path/to/Helper.js'
// or just a helper function (that should be exported accordingly
import { helperFunction } from 'relative/path/to/Helper.js'

export default {
   name: 'TestComponent'
   // component data, methods, etc are now able to use imported variables 
}
</script>
Run Code Online (Sandbox Code Playgroud)

这样您就可以在组件内使用任何其他 JS。Webpack 会将其包含在捆绑包中。但是,如果在许多组件中使用库,维护或重复导入可能会变得不舒服。在这种情况下,可以在创建 Vue 实例的主应用程序文件内的 Vue 原型上定义库,这将使其可以从任何组件访问。

import moment from 'moment'; Object.definePrototype(Vue.prototype, '$moment', { value: moment });

请关注文章以获取详细说明和更好的实践。