Meteor Blaze 在 table 中显示对象的动态值

Meteor Blaze display dynamic values of an object in a table

我是 Meteor 的新手,我想在 table 中显示对象的一些结果,值和行根据结果而变化,格式如下:

obj={10: [“1”, “3”, “0”, “0”]
11: [“1”, “7”, “0”, “0”]
12: [“1”, “12”, “0”, “0”]}

所以数据是动态的但不是一个集合,数组的每个元素都是 table 的一个单元格,从上面的例子我需要一个 table 有 3 行和 5 列

根据我目前阅读的内容,我的目标是:

aslagle:reactive-table

它也可以用于编写的普通数组。对于我想在 table 中显示的内容,这是正确的路径还是太复杂了,有什么建议吗?

您可以使用 ReactiveVar 或 ReatciveDict 来响应式显示数据。首先,您需要使其可迭代。最好是在 Template.onCreated 函数中执行此操作。假设您的模板名称为 "myTable":

Template.myTable.onCreated(function onMyTableCreated() {
  const instance = this
  instance.state = new ReactiveDict()
  instance.state.set('entries', [])

  instance.autorun(() => {
    const obj = // ... however you get your object
    const entries = Object.keys(obj).mapkey => ({
      key:key,
      value: obj[key]
    }))
    instance.state.set('entries', entries)
  })
})

现在您可以定义一个助手,returns您已经处理过的条目以正确的格式添加到您的模板中:

Template.myTable.helpers({
  entries() {
    return Template.instance().state.get('entries')
  }
})

现在您可以轻松地遍历您的条目及其值:

<template name="myTable">
  <table>
  <thead>
    <tr>
    {{#each entries}}
      <th>{{this.key}}</th>
    {{/each}}
    </tr>
  </thead>
  <tbody>
  {{#each entries}}
    <tr>
      <!-- this.value is the array, such as [“1”, “3”, “0”, “0”] -->
      {{#each this.value}}
      <td>{{this}}</td>
      {{/each}}
    </tr>
  {{/each}}
  </tbody>
  </table>
</template>

从这里带走的东西:

  • 对象需要重构为可迭代结构
  • 重构应该在 onCreated - auto运行 中完成(它只在数据改变时重新 运行s)而不是在 helpers 中(它可以在渲染中多次 运行周期)。
  • 实现自己的 table 有助于学习 Blaze 的基础知识
  • 使用包处理复杂的任意数据(注意学习曲线)