【问题标题】:Format Datetime from array using momentjs使用 momentjs 从数组格式化日期时间
【发布时间】:2018-11-24 20:52:48
【问题描述】:

我有这样的vue tables 2

<template>
 <v-server-table url="/"
                      :columns="orderListColumns"
                      :options="orderListOptions">
 </v-server-table>
</template>

import moment from 'moment';
import { Event } from 'vue-tables-2';

export default {
  name: 'order-list',

  components: { FontAwesomeIcon, LoaderIcon },

  mixins: [i18nMixin, userMixin],

  data() {
    return {
      query: '',
      orderList: [],
      orderListColumns: [
        'productDetailName',
        'email',
        'orderId',
        'orderDate',
        'type',
        'paymentStatus',
        'total',
      ],
      isDataLoading: false,
    };
  },

  computed: {
    orderListOptions() {
      return {
        uniqueKey: 'orderId',
        perPageValues: [],
        sortable: [],
        requestFunction: ({ page, limit, query }) =>
          orderService.getOrdersByUser(
            OrderSelectModel({
              mcUserName: this.$_user.userName,
              rowsPerPage: limit,
              pageNumber: page - 1,
              languageId: this.$_i18n_currentLanguageId,
              code: query,
            })
          ),
       responseAdapter: ({ order, totalItems }) => {
      const o = order;
      const orderDate = moment(order.orderDate).format('MMMM Do YYYY');
       o.orderDate = orderDate;
        return {
        data: o,
        count: totalItems,
         };
        },
            //etc

正如您在 responseAdapter 上看到的,我将数据分配为 data: o 问题是当我收到 orderDate 字段时,我收到的是:2018-06-12T19:58:41.73 并且我想使用 momentjs 来格式化它,所以在响应适配器中我尝试:

    responseAdapter: ({ order, totalItems }) => {
      const o = order;
      const orderDate = moment(order.orderDate).format('MMMM Do YYYY');
      o.orderDate = orderDate;
      return {
        data: o,
        count: totalItems,
      };
      },

但它不起作用,它只是没有格式化日期。我究竟做错了什么?问候

【问题讨论】:

    标签: vue.js vuejs2 momentjs vue-tables-2


    【解决方案1】:

    我认为order是一个数组,你需要循环遍历它

    responseAdapter: ({ order, totalItems }) => {
      const formatOrder = order.map(o => {
        const orderCopy = JSON.parse(JSON.stringify(o))
        orderCopy.orderDate = moment(o.orderDate).format('MMMM Do YYYY')
        return orderCopy
      })
      return {
        data: formatOrder,
        count: totalItems
      };
    }
    

    如果你使用的是 ES6,语法会更短

    const formatOrder = order.map(o => {
      const orderDate = moment(o.orderDate).format('MMMM Do YYYY')
      return {...o, orderDate}
    })
    

    【讨论】:

    • 我试了一下,但我得到了http://eslint.org/docs/rules/no-param-reassign Assignment to property of function parameter 'o'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多