【问题标题】:VueJs: importing custom js librariesVueJs:导入自定义 js 库
【发布时间】:2018-01-11 21:08:15
【问题描述】:

我有一个使用 vue-cli webpack 启动的 VueJS 项目。我有一个 javascript 库,其中包含我在所有组件中需要的功能。我想知道我需要把这个文件夹放在哪里,以及如何从 Component1.vue 中的 JSLibrary1 调用函数:

-myJSLibrary
    JSLibrary1.js
    JSLibrary2.js

JSLibrary1.js

var A = A || (function() {
    class B {
        function C(){
            return “hello”;
        }   
    }       
    var obj = new B();
    return obj;
}());

项目结构

VueProject
   build
   config
   src
    assets
    components
        Component1.vue
    App.vue
    main.js
   static

谢谢。

【问题讨论】:

  • 由于你使用的是 vue-cli,你可能也在使用 webpack。首先看看Single File Components 和Webpack: Getting Started。
  • 如果你有 webpack,你可以使用 import 来包含外部 JavaScript 代码,但你的库也应该 export 它的函数/类。您也可以在 HTML 中加载带有 <script> 标记的 javascript 文件

标签: javascript vue.js libraries


【解决方案1】:

libraries.js

export const A = () => {
  // your code
}

export const B = () => {
  // your code
}

Component1.vue

<script>
import { A, B } from '~/path/to/libraries.js'
export default {
  data () {
    return {}
  },
  mounted () {
    // execute A when components is rendered
    A()
  }    
</script>

【讨论】:

  • 很好,但是.....有没有可能在不导出其属性的情况下在模块中使用libraries.js?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-15
  • 1970-01-01
  • 2013-12-01
  • 2012-01-19
  • 2021-11-24
  • 1970-01-01
  • 2012-01-15
相关资源
最近更新 更多