"Undefined 'blogItems' error" while trying to push updates to Vue data variables
P粉262073176
P粉262073176 2023-09-15 23:28:14
0
1
520

I'm trying to get all the posts from Firebase and add them to an array, but I'm getting the following error:

Uncaught (in promise) TypeError: Cannot read property 'blogItems' of undefined

The following is the script:

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粉262073176
P粉262073176

reply all(1)
P粉835428659

In your case, change this in this.blogItems to posts.

You have two solutions

  1. Store this into a variable and use it

    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)
       })
     })
    
     },

  1. Use arrow functions

    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)
       })
     })
    
     },
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!