简体   繁体   中英

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. So I have 2 files where I want to use my function like this :

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. 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 :

MetaData.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.

Here's a JSFiddle as an example: https://jsfiddle.net/c5takojL/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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