格式化 Vuex 对象值的方法

Saj*_*jax 2 vue.js vuex

我试图了解如何在 Vuex 存储中使用值并进行一些格式化,关键是我试图找出 Vue 方法来格式化存储中对象中包含的时间戳并在迭代对象时。

例如使用以下商店

 const state = {
   events: {
     0: {
       id: 0,
       name: 'Example Event',
       start: 14907747374,
       end: 14907747674,
       entries: [0, 1]
     },
     1: {
       id: 1,
       name: 'Example Event 2',
       start: 14907740364,
       end: 14907740864,
       entries: [1]
     }
   },
   entries: {
     0: {
       id: 0,
       name: 'John Doe',
     },
     1: {
       id: 1,
       name: 'Paul Smith'
     }
   }
 }
Run Code Online (Sandbox Code Playgroud)

然后我有一个 getter 来返回所有事件

export const events = state => state.events
Run Code Online (Sandbox Code Playgroud)

然后我想在组件中将事件显示为列表/表格等

<template>
  <div class="events">
    <template v-for="event in getAllEvents">
       <div class="event>
         {{ event.name }} || {{ event.start }}
       </div>
    </template>
  </div>
</template>

<script>
  export default {
    name: 'events',
    computed: {
      getAllEvents: function () {
        return this.$store.state.events
      }
    }
  }
</script>
Run Code Online (Sandbox Code Playgroud)

所以这会显示

Example Event || 14907747374
Example Event 2 || 14907740864
Run Code Online (Sandbox Code Playgroud)

而我需要显示

Example Event || Jan 3rd 2017 14:15
Example Event 2 || Jan 3rd 2017 14:45
Run Code Online (Sandbox Code Playgroud)

因此,在 v-for 中,我想将“event.start”时间戳格式化为人类可读的日期,而我不确定哪种方法是 Vue 的做法。

过滤器

我以前用 Angular 1 过滤器做过类似的工作,但是我对 Vue 过滤器的理解是它们特定于组件,而它们在 Angular 1 中随处可用。格式化日期似乎是一项常见任务,我应该能够编写单个函数并在任何需要的地方使用它。我可以在另一个模块中编写函数并将其导入到组件中,但我仍然需要在我希望使用它的每个组件中编写过滤器,但至少逻辑是分开的。

组件方法函数

与此处的过滤器相同的问题,逻辑可以是单独的功能,但我仍然有过滤器本身的重复

单独的组件

可能是我想到的最好的解决方案,但感觉像是滥用组件来实现这样的次要功能

<template>
  <span>{{ formattedDate }}</span>
</template>

<script>
  import 'moment'
  export default {
    name: 'humanDate',
    props: ['timestamp'],
    computed: {
      formattedDate: function () {
        return moment(timestamp).format()
      }
    }
  }
</script>
Run Code Online (Sandbox Code Playgroud)

然后使用组件

<human-date timestamp="event.start"></human-date>
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法我错过了,并且正在为小事情创建组件,例如合理使用组件?

Pat*_*ele 5

查看Mixins。我创建了一个 quick-n-dirty mixin,用于使用moment.js格式化日期:

import moment from 'moment'

export default {
    formatDateMixin: {
        methods: {
            formatDate: function(value) {
                if( !value) return '';

                return moment(value).format('YYYY-MM-DD HH:mm:ss');
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

将它插入到你的主 Vue 实例中:

Vue.mixin(formatDateMixin);
Run Code Online (Sandbox Code Playgroud)

现在你可以在任何模板中使用它:

{{ event.name }} || {{ formatDate(event.start) }}
Run Code Online (Sandbox Code Playgroud)