How can I use global functions in Vue?

Viewed 2410

I have a date formatting function. Now I need to use this method in different components. What's the best practice for this situation? Directive? Filters? Or something different? How can I define this?

dateWithoutTime(date) {
  return date ? date.split("T")[0] : ""
}
1 Answers

Module

Assuming you're using Vue CLI or an equivalent bundler, the way that is most composable would be to create a module for utility functions like:

utilities.js

export const dateWithoutTime = function(date) {
  return date ? date.split("T")[0] : ""
}

Then you could import that function wherever you need it:

SomeComponent.vue

import { dateWithoutTime } from '@/modules/utilities.js'

export default {
  data: () => ({
    someDate: new Date()
  }),
  methods: {
    someMethod() {
      return dateWithoutTime(this.someDate);
    }
  }
}

Edit: You could also make it a method to use it directly from the template:

methods: {
  dateWithoutTime      // Same as `dateWithoutTime: dateWithoutTime`
}

Vue.prototype

Another option is to set the function on Vue.prototype prior to instantiating your app:

main.js

Vue.prototype.$dateWithoutTime = function(date) {
  return date ? date.split("T")[0] : ""
}

new Vue({
...
})

Then the function can be used in any component like:

SomeComponent.vue

export default {
  data: () => ({
    someDate: new Date()
  }),
  methods: {
    someMethod() {
      return this.$dateWithoutTime(this.someDate);
    }
  }
}
Related