[Vuejs]-How to change array within a method using vuejs

0👍

Use arrow functions as they use the lexical scope of the parent, in this case the scope of the changeStudents function, thus “this” refers to the the component instance, and students data property is then available.

studentsCol.get().then((querySnapshot) => {
        querySnapshot.forEach((doc) => {
          var student = doc.data();
          newStudents.push(student);

          // line below doesn't work because it doesn't know this.students
          // this.students.push(student);
          }
        });
      });

The forEach loop sets its own context, and “this” is overridden then, arrow functions solve this. However, if you don’t want to use arrow functions, you can pass a context to the forEach loop, like this:

array.forEach(function(param) {
  // code
}, this);

Leave a comment