我对Angular的Vue.js完全陌生。我尝试加载asyncData并显示如下:
<template>
<section>
<h1 v-for="employee in employees" v-bind:key="employee.name"> {{employee.name}}</h1>
</section>
</template>
<script>
import { db } from '../firebase.js'
import { Employee } from "../models/employee.js";
import { Entry } from "../models/entry.model.js";
export default {
data: function() {
return { employees: [] };
},
created: function() {
this.loadEmployees();
},
methods: {
loadEmployees: function() {
db.collection('Employees').get().then(
(snapshots) => {
for (const doc of snapshots.docs) {
const e = new Employee(doc.data().name, doc.data().worktimes);
e.id = doc.id
this.employees.push(e);
}
}
)
},
}
}
</script>
对我来说,这似乎很简单,但是v-for
加载后不会显示数据。关于不知道的Vue和异步数据,我需要了解些什么吗?我真的找不到任何有用的东西。
答案 0 :(得分:3)
每次for (const doc of snapshots.docs)
的迭代都将覆盖整个员工阵列。将employees
的本地声明移出循环,并在末尾重新分配。
{
loadEmployees: function() {
db
.collection('Employees')
.get()
.then(snapshots => {
const employees = [];
for (const doc of snapshots.docs) {
const e = new Employee(doc.data().name, doc.data().worktimes);
e.id = doc.id
employees.push(e);
}
this.employees = employees;
/*
* As an alternative, you could just use .map()
* which creates the new array, pushes to it,
* and assigns all in one compact function
*/
this.employees = snapshots.docs.map(doc => {
const {
name,
worktimes
} = doc.data();
const e = new Employee(name, worktimes);
e.id = doc.id;
});
})
}
}