7

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] : ""
}
2
  • 1
    Create a mixin and put the function (method) inside it then just include the mixin where you need that function. Commented Feb 11, 2021 at 9:28
  • Note that mixins are an anti-pattern and were eliminated in Vue 3, best not to use one. Commented Mar 10, 2023 at 3:38

1 Answer 1

12

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);
    }
  }
}
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.