【问题标题】:How to use Moment.js with Vuexfire如何在 Vuexfire 中使用 Moment.js
【发布时间】:2020-05-11 05:01:28
【问题描述】:

我正在构建一个在 store.js 文件中使用 Vuexfire 的 Vue.js 应用程序。我的应用程序使用户能够将用户输入的带有时间戳的帖子推送到 Firestore。我正在配置我的 Vuexfire 操作处理程序,以提交按时间戳顺序排列的 firebase 有效负载的突变,如下所示:

import Vue from "vue";
import Vuex from "vuex";
import firebase from "firebase";
import { vuexfireMutations, firestoreAction } from 'vuexfire'
import { db } from "@/main";
import moment from 'moment'

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    posts: []
  },
  mutations: {
    ...vuexfireMutations
  },
  actions: {
    setAllPost: firestoreAction(context => {
      return context.bindFirestoreRef('posts', db.collection('posts').orderBy('timestamp'))
    })
  }
});

此设置按时间戳正确排列帖子。但是,我希望使用 Moment.js 格式化时间戳,但不确定如何将 Moment 正确应用于动作处理程序。我尝试将时间戳包装在 Moment 中,如下所示:

  actions: {
    setAllPost: firestoreAction(context => {
      return context.bindFirestoreRef('posts', 
      db.collection('posts').orderBy(moment('timestamp').format('lll')))
    })
  }

...但这没有返回任何输出,只有控制台中的警告。我还尝试设置输入组件,以便推送到 Firebase 的时间戳已经使用 Moment 进行格式化,但帖子没有以正确的顺序返回。 知道如何在 Vuexfire 操作处理程序中正确设置 Moment.js 以格式化时间戳吗?谢谢!

【问题讨论】:

    标签: firebase vue.js vuex vuefire vuexfire


    【解决方案1】:

    我找到了使用filters 属性的解决方案:

    <p>{{ post.timestamp | moment }}</p>
    
    
    filters: {
      moment: function (date) {
        return moment(date).format('lll')
      }
    },
    

    这工作正常。我仍然想知道是否有办法在 Vuexfire 操作处理程序中使用 Moment.js。这可能吗?

    【讨论】:

      【解决方案2】:

      您不能在 Firestore 中应用此类排序。 orderBy() 接受一个字符串,该字符串是您要用作订单库的属性的名称或它的路径(TS 类型 fieldPath: string | firestore.FieldPath)。

      https://firebase.google.com/docs/firestore/query-data/order-limit-data

      要格式化您必须在客户端执行的日期,就像您正在做的那样,或者以您希望的格式保存日期,然后按它排序。

      【讨论】:

        猜你喜欢
        • 2018-10-14
        • 2013-01-18
        • 2013-02-25
        • 2019-09-11
        • 2012-06-13
        • 2014-01-12
        • 2021-02-04
        • 2016-07-28
        • 2017-03-18
        相关资源
        最近更新 更多