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.
-
Sounds like you just need webpack to be able to resolve your imports and exports.Christopher Francisco– Christopher Francisco2017年11月21日 19:01:36 +00:00Commented Nov 21, 2017 at 19:01
-
check this out: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Christian– Christian2017年11月21日 19:04:00 +00:00Commented Nov 21, 2017 at 19:04
-
I use webpack soo how can i do that ?Adrien Roussel– Adrien Roussel2017年11月21日 19:04:31 +00:00Commented Nov 21, 2017 at 19:04
1 Answer 1
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/
2 Comments
babel-loader being applied to your .js files files in your webpack config.