如何在 Vuexfire 中使用 Moment.js [英] How to use Moment.js with Vuexfire

查看:31
本文介绍了如何在 Vuexfire 中使用 Moment.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am building a Vue.js application that uses Vuexfire in a store.js file. My application enables a user to push user-inputted posts with timestamps into Firestore. I am configuring my Vuexfire action handler to commit to mutation the firebase payload arranged in order by timestamp, like so:

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 中包装时间戳,如下所示:

This setup properly arranges the posts in order by timestamp. HOWEVER, I wish to format the timestamps with Moment.js, but am not sure how to properly apply Moment to the action handler. I tried wrapping the timestamp in Moment, like so:

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

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

...but this returned no output, only a warning in the console. I also tried setting up the input component so that the timestamp pushed into Firebase is already formatting with Moment, but the posts did not return in the correct order. Any idea how I can properly set up Moment.js in the Vuexfire action handler to format the timestamp? Thanks!

推荐答案

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

You cannot apply such kind of ordering in firestore. orderBy() accepts a string which is the name of the property you want to use as an order base or the path to it (TS type fieldPath: string | firestore.FieldPath).

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

要格式化日期,您必须像现在一样在客户端执行此操作,或者以您希望的格式保存日期,然后按它排序.

To format the dates you have to do it client-side just like you are doing, or saving the dates in the format you wish and then ordering by it.

这篇关于如何在 Vuexfire 中使用 Moment.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆