【问题标题】:Vue: Async Data is not being rerenderedVue:异步数据没有被重新渲染
【发布时间】:2018-09-07 19:16:43
【问题描述】:

我对来自 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 和异步数据,我需要了解一些我不知道的事情吗?我真的找不到任何有用的东西。

【问题讨论】:

  • @zero298 你说得对。我尝试覆盖以查看是否解决了我的问题,但没有解决。我只是在发布时忘记更正它
  • 在所有迭代之后,您仍然需要分配回dataemployees。所以把this.employees = employees;放在for循环之后,把const employees = [];移出for循环。

标签: firebase vue.js


【解决方案1】:

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

【讨论】:

  • 是的,我刚刚回答了你的评论。我尝试覆盖以查看是否解决了我的问题,但没有解决。我只是在发布此内容时忘记更正它
  • 您能否更正原始帖子,以便我们看到const employees 声明和this.employees 分配。除了这个答案所建议的之外,我没有看到明显的问题。
  • 看起来应该可以了。我的下一步是查看 VueDevTools 中的数据对象和/或将控制台日志消息放入 for 循环中以确保它被调用。还要确保定义了 name 属性(模板中实际使用的)。
  • 我的意思是,这应该只是一个地图操作。
  • @Martin 该死的,我在员工构造函数中犯了一个小错误,所以我的doc.data().name 实际上并没有分配给employee.name。感谢您帮助查找问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-13
  • 2018-05-19
  • 2023-01-10
  • 1970-01-01
  • 2020-01-22
  • 1970-01-01
  • 2019-02-03
相关资源
最近更新 更多