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

查看:114
本文介绍了如何在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天全站免登陆