简体   繁体   English

使用来自外部 javascript 文件的函数

[英]Use function from external javascript file

Hi everyone I work on webpack and VueJS and I want to use a function in multiple different scripts but I don't want to write the script of these function many times.大家好,我在 webpack 和 VueJS 上工作,我想在多个不同的脚本中使用一个函数,但我不想多次编写这些函数的脚本。 So I have 2 files where I want to use my function like this :所以我有 2 个文件,我想像这样使用我的函数:

export default {
    data(){
        return {
            metadata: null,
        }
    },
    methods:{

    },
    mounted(){
             this.metadata = this.httpGet("myurl");


    }
}

And like this :像这样:

export default {
    data(){
        return {
            metadata: null,
        }
    },
    methods:{

    },
    mounted(){
             this.metadata = this.httpGet("myurl");


    }
}

And this is the third part where i want to create my function :这是我要创建函数的第三部分:

httpGet(theUrl){
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.open("GET", theUrl, false); // true for asynchronous request
        xmlHttp.send(null);
        return JSON.parse(xmlHttp.responseText);

}

I don't found the exact code to make it works.我没有找到使它工作的确切代码。 So please tell me how I can use imports, require or things like this.所以请告诉我如何使用导入、要求或类似的东西。 I don't want to use vuex because it is to complex for the little thing I want to do.我不想使用 vuex,因为它对于我想做的小事来说太复杂了。 The final objective is to get a script where I can store different functions and use them in multiples others scripts.最终目标是获得一个脚本,我可以在其中存储不同的函数并在多个其他脚本中使用它们。

For this you can just use a mixin :为此,您可以使用mixin

MetaData.js元数据.js

const MetaData = {
    data(){
        return {
            metadata: null,
        }
    },
    methods:{
       httpGet(theUrl){
         var xmlHttp = new XMLHttpRequest();
         xmlHttp.open("GET", theUrl, false); // true for asynchronous request
         xmlHttp.send(null);
         return JSON.parse(xmlHttp.responseText);

      }
    },
    mounted(){
      this.metadata = this.httpGet("myurl");
    }
}

export default MetaData

Now in your component you can use it like so:现在在您的组件中,您可以像这样使用它:

<template>
  <div>{{metadata}}</div>
</template>

<script type="text/javascript">
  import MetaData from './mixins/MetaData' // wherever you have saved the mixin 

  export default{
    mixins: [MetaData]
  }
</script>

That will automatically merge the two objects together, so you can use all the instance properties in your mixin in your Vue component you imported it in to.这将自动将两个对象合并在一起,因此您可以在导入的 Vue 组件中使用 mixin 中的所有实例属性。

Here's a JSFiddle as an example: https://jsfiddle.net/c5takojL/这里以 JSFiddle 为例: https ://jsfiddle.net/c5takojL/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM