Categories
Vue Answers

How to Make Helper Functions Globally Available to Single-File Components with Vue.js?

Spread the love

Sometimes, we want to make helper functions globally available to single-file components with Vue.js.

In this article, we’ll look at how to make helper functions globally available to single-file components with Vue.js.

Make Helper Functions Globally Available to Single-File Components with Vue.js

We can create mixins to make helper functions globally available to single-file components with Vue.js.

For instance, we can write:

<template>
  <div id="app">
    {{ capitalizedName }}
  </div>
</template>

<script>
import Vue from "vue";

Vue.mixin({
  methods: {
    capitalizeFirstLetter: (str) => str[0].toUpperCase() + str.slice(1),
  },
});
export default {
  name: "App",
  data() {
    return {
      name: "james",
    };
  },
  computed: {
    capitalizedName() {
      return this.capitalizeFirstLetter(this.name);
    },
  },
};
</script>

We call Vue.mixin with an object to make our own mixin.

It creates a global mixin so it’ll be available to all components automatically.

In the object, we have the methods property which is set to an object with some component methods.

It has the capitalizeFirstLetter method which takes a string and returns a string with the first letter capitalized.

Next, we return the name reactive property in the data method.

And then we create the capitalizedName computed property which calls the capitalizeFirstLetter method from the mixin with this.name and returns the returned result.

Next, we add capitalizedName to the template to render it.

And we see ‘James’ displayed as a result.

Conclusion

We can create mixins to make helper functions globally available to single-file components with Vue.js.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *