Heim  >  Fragen und Antworten  >  Hauptteil

„Undefinierter ‚blogItems‘-Fehler“ beim Versuch, Aktualisierungen an Vue-Datenvariablen zu übertragen

Ich versuche, alle Beiträge von Firebase abzurufen und einem Array hinzuzufügen, erhalte jedoch die folgende Fehlermeldung:

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

Hier ist das Skript:

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粉262073176P粉262073176371 Tage vor486

Antworte allen(1)Ich werde antworten

  • P粉835428659

    P粉8354286592023-09-16 00:09:32

    在你的情况下,将this.blogItems中的this更改为posts

    你有两种解决方法

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

    1. 使用箭头函数

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

    Antwort
    0
  • StornierenAntwort