0

I have this function in a Vuejs File which calls another function which is imported from a JS File.

Demo.vue

import Data from "demofile.js"

created(){
  this.getResult()
}

methods(){
async getResult(){
      Data.example() // Fetching Data from API
      .then((results) =>{
        this.$set(this,"results",results) // storing in event data()
        console.log(this.results)
    })
    .catch(e =>console.log(e, "Error from catch"))
  }
 }

I want to make this function reusable so that I could use it on any other VueJS files.

2 Answers 2

2

Alternative solution which I like more.

Create inside src/ a folder with name utils and inside the folder create .js file like globalFunctions.js and add the method

export const consoleLogName = (input) => {
    console.log(input)
  }

And then in Component.vue import the file:

import { consoleLogName} from "@/utils/globalFunctions";

and register the method in methods like:

methods:{
 consoleLogName: consoleLogName,
 otherMethodhere(){
  ......
 }
}

or with desctructuring providing the same name, this is a shortcut:

 methods:{
     consoleLogName,
     otherMethodhere(){
      ......
     }
 }

and use it in template as a regular method:

<template>
 <div>
  <span @click="consoleLogName('My Name')"></span>
 </div>
</template>
Sign up to request clarification or add additional context in comments.

Comments

0

You can use mixins to re-use your functions in other Vue.js files.

Official documentation: https://v2.vuejs.org/v2/guide/mixins.html

Comments

Your Answer

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.