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



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

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

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

从我目前所读到的内容来看,我的目标是:

aslagle:反应表

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

您可以使用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)
})
})

现在,您可以定义一个助手,以正确的格式将已处理的条目返回到模板:

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-autorun中完成(只在数据更改时重新运行(,而不是在助手中完成(可以在渲染周期中运行多次(
  • 实现自己的表格有助于学习Blaze的基础知识
  • 使用包处理复杂的任意数据(注意学习曲线(

最新更新