问题
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'))
})
}
});
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')))
})
}
...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!
回答1:
I found a solution using a filters
property:
<p>{{ post.timestamp | moment }}</p>
filters: {
moment: function (date) {
return moment(date).format('lll')
}
},
This works OK. I would still like to know if there is a way to use Moment.js inside a Vuexfire action handler. Is that possible?
回答2:
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.
来源:https://stackoverflow.com/questions/59903702/how-to-use-moment-js-with-vuexfire