Vue:异步数据未重新渲染
2018-09-07
189
我从 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 和异步数据但我不知道的东西吗?我真的找不到任何有用的东西。
1个回答
每次
for (const doc of snappings.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;
});
})
}
}
zero298
2018-09-07