前提・実現したいこと
ページをロードする際(created()もしくはmouted()中で処理することを想定)にstoreに保存してあるstateの値を取得したい。
storeの値が正しく展開される前にfirebaseの処理が実行されてしまいます。
発生している問題・エラーメッセージ
取得した値がオブジェクトの状態で返ってくる(想定は文字列)
該当のソースコード
thread.vue
vue
1 mounted () { 2 this.openThread(this.$store.state.contents.topic) 3 }, 4 methods: { 5 openThread (docName) { 6 this.initInfo() 7 firebase.firestore().collection('chat-room').doc(docName) 8 .collection('messages').orderBy('timestamp', 'asc').onSnapshot(querySnapshot => { 9 querySnapshot.docChanges().forEach(change => { 10 console.log('doc:', change.type) 11 if (change.type ==='added') { 12 this.threadData.unshift({ 13 author: change.doc.data().author, 14 authorid: change.doc.data().authorid, 15 profileImage: change.doc.data().profileImage, 16 data: change.doc.data().message, 17 timestamp: change.doc.data().timestamp 18 }) 19 } 20 }) 21 }) 22 this.alertText = docName + 'ルームにようこそ!' 23 }, 24 }
store/contents.js
javascript
1export const strict = false 2 3export const state = () => ({ 4 topic: {}, 5}) 6 7export const getters = { 8 topic: state => { 9 return state.topic 10 }, 11} 12 13export const mutations = { 14 setTopic (state, value) { 15 state.topic = value 16 }, 17} 18 19export const actions = { 20 setTopic ({commit}, value) { 21 commit('setTopic', value) 22 }, 23} 24 25
試したこと
ソース中に記載のopenThread()関数をボタンイベントから呼ぶとstoreの値が文字列で返ってくるため、実行が成功します。”storeの値の展開処理が非同期であるためmounted()でstoreの値が展開されることが保証されていない”という性質から本現象が起きていると考えていますが、ではどうすれば良いのか というところがわかりません。
computed()でstoreの値が変化した際に実行する事も考えましたがopenthread()関数はページロード時に1度だけ呼びたいので、やりたいことがうまく実現できませんでした。
何か良い手法がありましたらご教授のほどよろしくお願いいたします。
あなたの回答
tips
プレビュー