Search code examples
javascripttypescriptvue.jsvuejs2date-fns

How to use date-fns with Vue class component?


Vue component:

<template>
  <div class="doc">
    {{ format(2019-08-11T08:13:13.750007, 'DD/MM/YYYY') }}
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import format from 'date-fns/format'

@Component
export default class Document extends Vue {
  public format: string | number | Date = ''
}
</script>

Throws an error: Error in render: "TypeError: _vm.format is not a function"

I suspect it's because format is considered a Document class property, and not the method from date-fns. How do I fix that? In plain JavaScript, it worked out of the box.


Solution

  • Instead of the class property, declare format as a class method that invokes the imported function:

    import { Component, Vue } from 'vue-property-decorator'
    import format from 'date-fns/format'
    
    @Component
    export default class Document extends Vue {
      format(date: string | number | Date, dateFormat: string): string {
        return format(date, dateFormat)
      }
    }