<input type="text" id="nameInput" maxlength="20" v-model="name"> </div> <div class="message-form-group"> <label for="messageInput">ϝοηʔδ</label> <input type="text" id="messageInput" maxlength="100" v-model="message"> </div> <button type="button" @click="sendMessage">ૹ৴</button> </div> <div> <ul class="message-list"> <li v-for="(item, key) in messageList" v-bind:key="key"> <p> {{item.message}} by {{item.name}} </p> <p class="time-label"> {{item.createdAt}} </p> </li> </ul> </div> </div> </template> <script> import firebase from 'firebase'; import database from '@/firebase-config'; export default { name: 'Top', data() { return { name: '', message: '', messageList: [], }; }, created() { this.listen(); }, methods: { listen() { database .ref('messages/') .on('value', (snapshot: firebase.database.DataSnapshot | null) => { if (snapshot) { const list = snapshot.val(); const keys = Object.keys(list); const values = keys.map((v) => list[v]); this.messageList = values.sort((a: Message, b: Message) => { if (a.sortKey > b.sortKey) return 1; if (a.sortKey < b.sortKey) return -1; return 0; }); } }); }, sendMessage() { if (!this.name || !this.message) return; const message = { name: this.name, message: this.message, createdAt: moment(new Date()).format('YYYY/MM/DD H:mm:ss'), sortKey: -new Date(), }; database.ref('messages/').push(message); this.name = ''; this.message = ''; } }, }; </script>