Home » vue » Call function from imported helper class in Vue.js component data

Call function from imported helper class in Vue.js component data

Posted by: admin November 26, 2021 Leave a comment

Questions:

I am trying to call a JavaScript function from an imported helper class in my Vue.js component. I import my helper class in my component and try to use mounted() to call it and pass a paramter to the helper class.

I tried out some solutions from here, but didn’t help:
Vue.js: Import class with function and call it in child component

https://forum.vuejs.org/t/how-to-use-helper-functions-for-imported-modules-in-vuejs-vue-template/6266

This is what I tried so far, any ideas?

I have a helper class myHelper.js:

export default myHelper {
    myHelperFunction(param) {
        return param;
    }
}

I have a Vue component MyComponent.vue:

<template>
  <v-text-field :rules="[myRule]"></v-text-field>
</template>

<script>
import myHelper from './myHelper.js';

export default {
  name: 'MyComponent',
  data() {
    return {
      myCls: new myHelper(),
      myRule: this.callHelperFunction,
    };
  },
  components: {
    myHelper,
  },
  mounted() {
    this.myCls.myHelperFunction();
  },
  methods: {
    callHelperFunction(param) {
      this.myCls.myHelperFunction(param);
    }
  },
};
</script>
Answers:

You are not really exporting the class. It is a plain object. To export a class instead of an object do this:

// Notice the use of class keyword
export default class MyHelper {
    myHelperFunction(param) {
        return param;
    }
}

Also, you do not need:

components: {
    myHelper,
},

Rest of the code stays the same.