1

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.

asked Nov 21, 2017 at 18:52
3

1 Answer 1

2

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/

tony19
140k24 gold badges281 silver badges354 bronze badges
answered Nov 21, 2017 at 19:33
Sign up to request clarification or add additional context in comments.

2 Comments

I'm not sure it works in the web pack environement. It says : ncaught ReferenceError: Metadata is not defined. It is like if const Metadata in my js file didn't worked.
Make sure you have babel-loader being applied to your .js files files in your webpack config.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.