简体   繁体   中英

how can i order by snapshot's child data containing a timestamp index with vue js

I saved the timestamp as a data field inside firebase DB, this way I can now retrieve it like {{ post.timestamp }} to display it, how would I go from where I am at to order the posts by timestamp order regardless of the user object order, for example, what I get in the UI is the posts ordered by the user and not by time.

data on firebase looks like this:

在此处输入图像描述

Code looks like this:

    <template>
    <div>
           <div
           v-for="post in allPosts.slice().reverse()"
           :key="post._key">
           <v-card class=" feed-card my-3">
           <v-row no-gutters>
           <v-col cols="1">
           <v-img
           class="align-center rounded-xl "
           width="30"
           :src="post.photoURL">
           </v-img>
           </v-col>
           <v-col cols="10">
             <p class="">{{post.postText}}</p>
             <p class="blue-grey--text ">{{post.displayName}}</p>
             <p class="mb-n1 mt-n5 d-flex flex-row-reverse"> {{post.date}} {{post.time}}</p>
             </v-col>
             </v-row>
       </v-card>
     </div>
   </div>
</template>
<script>
import firebase from '@/plugins/firebase'

let db = firebase.database();
//let usersRef = db.ref('users');
let postRef = db.ref('posts');
export default {
  name: 'FintechSocialFeed',
  data: () => ({
  authUser: null,
  allPosts: [] // initialise an array
}),
  methods: {
  },
  created: function() {
    data => console.log(data.user, data.credential.accessToken)
    firebase.auth().onAuthStateChanged(user => {
        if (user) {
          postRef.on('value', snapshot => {
            const val = snapshot.val()
            if (val) {
              this.allPosts = Object.values(val).flatMap(posts =>
              Object.entries(posts).map(([ _key, post ]) => ({ _key, ...post})))
            }
            console.log(snapshot.val())
          });
        }

     })
   }
}
</script>

here is the UI showing the latest post at the bottom because it is sorting by the user and not date:

在此处输入图像描述

I don't use firebase, but it looks like db reference provides orderByKey , so...

let postRef = db.ref('posts').orderByKey('timestamp');

An alternative would be sorting yourself, after retrieval...

this.allPosts = Object.values(val).flatMap(posts =>
    Object.entries(posts).map(([ _key, post ]) => ({ _key, ...post}))
).sort((a, b) => a.timestamp.toMillis() - b.timestamp.toMillis()); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM