简体   繁体   English

如何将 date-fns 与 Vue 类组件一起使用?

[英]How to use date-fns with Vue class component?

Vue component: Vue 组件:

<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"抛出错误: 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 .我怀疑这是因为format被认为是Document类属性,而不是date-fns的方法。 How do I fix that?我该如何解决? In plain JavaScript, it worked out of the box.在纯 JavaScript 中,它开箱即用。

Instead of the class property , declare format as a class method that invokes the imported function:代替 class property ,将format声明为调用导入函数的类方法

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM