How to access an externally imported method in a Vue.js component?

Sometimes, we want to access an externally imported method in a Vue.js component.

In this article, we’ll look at how to access an externally imported method in a Vue.js component.

How to access an externally imported method in a Vue.js component?

To access an externally imported method in a Vue.js component, we can use a mixin.

For instance, we write

<template>
  <div>
    <button type="button" name="button" @click="myFunc">
      Call External JS
    </button>

    ...
  </div>
</template>

<script>
import somethingMixin from "@/mixins/somethingMixin";

//...
export default {
  //...
  mixins: [somethingMixin],
  mounted() {
    this.myFunc();
  },
  //...
};
</script>

to incorporate the myFunc method from somethingMixin into our component.

We register the mixin in our component with

mixins: [somethingMixin]

Then we call this.myFunc in the mounted hook and also call myFunc when we click the button.

Conclusion

To access an externally imported method in a Vue.js component, we can use a mixin.