0

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>

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

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.