失礼します。
現在promiseとasync/awaitをざっくり理解したところでの質問になります。
やりたいこと
やりたいこととしては、pタグの中にfirebaseのcollectionから取得したusersデータのnameを取得して貼り付ける。といったことをしたいです。
ただ、現在いろいろ調べながらやってみて入るのですが、
- async/awaitを使うとビューテンプレートの中でthenをする必要が出てくるが、ビューテンプレートの中ではできない&できたら避けたい
- async/awaitを使わずにthen(function(){ここの中の変数を})外に出すにはどうしたらいいのかがわからない
抜粋コードをいかに貼り付けます。
vue
1<template> 2 <p>{{ getUser(item.userId) }}</p> 3</template> 4<script> 5// 省略 6export default { 7 methods: { 8 async getUser (userId) { 9 let db = firebase.firestore() 10 let usersRef = db.collection('users').doc(userId) 11 let res = await usersRef.get() 12 let name = res.data().name 13 console.log(name) 14 return name 15 } 16 } 17} 18</script> 19
一応年のため全体のコードも貼っておきます(ビューはpugになります。
html
1<template lang="pug"> 2v-ons-page 3 Navigation(@logout="logout" @pull="pull") 4 h1 chat index 5 p(v-if="!lists") まだ何も投稿されていません 6 v-ons-list(v-else) 7 v-ons-list-item(v-for="(item, index) in lists" :key="index") 8 p {{ getUser(item.userId) }} 9 p {{ item.comment }} 10 .comment-wrapper 11 .flex-wrapper 12 textarea(v-model="comment" class="textarea" placeholder="コメントを書く…") 13 v-ons-button.custom-button(@click="submitComment") 送信 14</template> 15<script> 16import firebase from 'firebase/app' 17import 'firebase/database' 18import 'firebase/firestore' 19import Navigation from '../../components/Navigation' 20export default { 21 name: 'ChatIndex', 22 data: () => ({ 23 lists: [], 24 comment: '' 25 }), 26 props: { 27 boardId: { 28 type: String, 29 default: '' 30 } 31 }, 32 components: { 33 Navigation 34 }, 35 created () { 36 this.database = firebase.database() 37 this.chatRef = this.database.ref('chat/' + this.userId) 38 this.database.ref('chat').on('value', (res) => { 39 var lists = [] 40 var values = Object.entries(res.val()) 41 values.forEach((items) => { 42 let item = items[1] 43 if (item.boardId === this.boardId) { 44 lists.push(item) 45 } 46 }) 47 this.lists = lists 48 }) 49 }, 50 computed: { 51 userId: function () { 52 return this.$store.state.user.data.uid 53 }, 54 user: function () { 55 return this.$store.state.user.data 56 } 57 }, 58 methods: { 59 async getUser (userId) { 60 let db = firebase.firestore() 61 let usersRef = db.collection('users').doc(userId) 62 let res = await usersRef.get() 63 let name = res.data().name 64 console.log(name) 65 return name 66 }, 67 submitComment () { 68 this.chatRef.set({ 69 userId: this.user.uid, 70 boardId: this.boardId, 71 comment: this.comment 72 }) 73 }, 74 pull () { 75 this.$emit('pop') 76 }, 77 logout () { 78 firebase.auth().signOut().then(() => { 79 this.$store.commit('user/logout') 80 this.$emit('reset') 81 }) 82 } 83 } 84} 85</script> 86<style lang="sass" scoped> 87 .comment-wrapper 88 position: absolute 89 bottom: 0 90 left: 0 91 .flex-wrapper 92 display: flex 93 .textarea 94 width: 80vw 95 .custom-button 96 width: 20vw 97</style> 98
以上。よろしくお願いします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/05/03 15:32