我正在尝试从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) }) }) },