Custom Module Setup
If you are working with Vue CLI or a similar bundler, the most efficient way to organize your utility functions is by creating a custom module. This module can house functions like:
utilities.js
export const getFormattedDate = function(date) {
return date ? date.split("T")[0] : ""
}
You can then easily import and use this function in any component:
SomeComponent.vue
import { getFormattedDate } from '@/modules/utilities.js'
export default {
data: () => ({
someDate: new Date()
}),
methods: {
transformDate() {
return getFormattedDate(this.someDate);
}
}
}
Edit: Alternatively, you can define it as a method for direct usage in template:
methods: {
getFormattedDate // Similar to `getFormattedDate: getFormattedDate`
}
Vue.prototype Extension
An alternate approach is to extend Vue.prototype
with the function before initializing your Vue app:
main.js
Vue.prototype.$getFormattedDate = function(date) {
return date ? date.split("T")[0] : ""
}
new Vue({
...
})
This function is now accessible in any component like:
SomeComponent.vue
export default {
data: () => ({
someDate: new Date()
}),
methods: {
transformDate() {
return this.$getFormattedDate(this.someDate);
}
}
}