我正在嘗試從Firebase獲取所有的帖子並將它們添加到一個數組中,但是出現了以下錯誤:
Uncaught (in promise) TypeError: Cannot read property 'blogItems' of undefined
以下是腳本:
export default { data(){ return{ blogItems: [] } }, mounted(){ this.getPosts(); }, methods:{ getPosts(){ database.collection('blog').doc('yP6aYXvisFbTsqtQ3MEfuyz6xYE3').collection('posts').get().then(snapshot =>{ const posts = snapshot.docs.map(doc => doc.data()) posts.forEach(function(post){ this.blogItems.push(post.content) }) }) }, } }
P粉8354286592023-09-16 00:09:32
在你的情況下,將this.blogItems
中的this
改為posts
。
你有兩種解決方法
將this
儲存到一個變數中並使用它
getPosts(){ let tis = this; database.collection('blog').doc('yP6aYXvisFbTsqtQ3MEfuyz6xYE3').collection('posts').get().then(snapshot =>{ const posts = snapshot.docs.map(doc => doc.data()) posts.forEach(function(post){ tis.blogItems.push(post.content) }) }) },
使用箭函數
getPosts(){ database.collection('blog').doc('yP6aYXvisFbTsqtQ3MEfuyz6xYE3').collection('posts').get().then(snapshot =>{ const posts = snapshot.docs.map(doc => doc.data()) posts.forEach((post) => { this.blogItems.push(post.content) }) }) },