Массив в методе данных обновляется в одном методе, но остается пустым в другом методе - PullRequest
0 голосов
/ 02 мая 2020

В моем приложении я пытаюсь обновить массив. Сначала я получаю данные из базы данных и добавляю их в массив, а другим способом хочу использовать этот массив. Но массив не обновляется.

Если я использую мой массив exerciseList в DOM, в нем есть данные, но в функции getExercises длина массива по-прежнему равна 0. Это похоже на то, как я запускаю метод перед добавлением данных в массив или что-то в этом роде.

Любая идея, почему это не работает?

data: () => ({
    exerciseList: []

});

created() {
    this.getDataBaseCollection("Exercise", this.exerciseList); // array gets information here
}
mounted() {
    this.getExercises();
},

methods: {
    getDataBaseCollection: function (CollectionName, list) {
        db.collection(CollectionName).onSnapshot(snapshot => {
            snapshot.forEach(doc => {
                list.push(doc.data());
            });
        });

    },

    getExercises: function () {
        console.log(this.exerciseList.length);  // length is 0 ?? array seems empty
    }
 },

Ответы [ 2 ]

1 голос
/ 02 мая 2020

Я думаю, что пропущенная часть ключа может обновлять переменную exerciseList компонента, а не аргумент list. Они не одна и та же переменная. Объекты передаются по ссылке, но массивы передаются в функции только по значению, что делает list его собственной переменной независимой от excerciseList. Это грубый код, который показывает несколько способов убедиться, что exerciseList обновлен, и как узнать, когда все значения находятся в массиве.

// include exerciseListLoaded to flag when all data is ready
data: () => ({
    exerciseList: [],
    exerciseListLoaded: false
});

created() {
    this.getDataBaseCollection("Exercise"); // array gets information here
}
mounted() {
    // based on timing of the `onSnapshot` callback related to `mounted` being called, this may likely still result in 0
    console.log("Mounted");
    this.getExercises();
},

watch: {
    // watch for all data being ready
    exerciseListLoaded () {
       console.log("All Loaded");
       this.getExercises();
    }
},

methods: {
    // be sure to update the exerciseList on the component
    getDataBaseCollection: function (CollectionName) {
        // being careful about `this` since within `onSnapshot` I suspect it will change within that function
        const componentScope = this;
        db.collection(CollectionName).onSnapshot(snapshot => {
            snapshot.forEach(doc => {
                componentScope.exerciseList.push(doc.data());
                // could also still update `list` here as well if needed
            });
            // setting this allows the component to do something when data is all loaded via the `watch` config
            componentScope.exerciseListLoaded = true;
        });

    },

    getExercises: function () {
        console.log(this.exerciseList.length);  // length is 0 ?? array seems empty
    }
 },
0 голосов
/ 03 мая 2020

когда вы используете this внутри функции, это относится к функции, а не к экземпляру vue, поэтому вы можете использовать, который может работать с вами:

getExercises() {
        console.log(this.exerciseList.length);  
    }
...