在Meteor中如何用ReactiveVar插入并展示值?需存储展示对象
修正Meteor中ReactiveVar存储键值对对象的实现
我来帮你搞定这个ReactiveVar的使用问题,你的需求是用它存一个{id: value, id2: value2}格式的键值对对象,然后根据key获取对应值对吧?原代码里有几个关键问题需要调整,我给你一步步捋清楚:
核心问题分析
- 异步回调里的
this指向错误:Meteor.call是异步的,回调函数里的this不再是模板实例,直接用this.test会找不到变量。 - ReactiveVar的赋值方式错误:你写的
this.test.set([parameterPassed] = res)语法不对,而且会直接覆盖整个对象,没法累积多个键值对。 - 取值方式错误:不能直接在
get()里传参数,得先拿到整个对象,再访问对应的属性。
正确实现代码
1. 设置值(模板的onCreated钩子中)
Template.yourTemplateName.onCreated(function () { // 初始化ReactiveVar为空对象 this.test = new ReactiveVar({}); // 保存模板实例引用,避免异步回调里this指向混乱 const instance = this; _.each(usms, function(usm) { const parameterPassed = usm; // 这里假设parameterPassed就是usm,根据你的实际情况调整 Meteor.call('functionName', parameterPassed, function(err, res) { if (!err) { // 1. 获取当前ReactiveVar里的对象 const currentData = instance.test.get(); // 2. 添加新的键值对(不覆盖原有数据) currentData[parameterPassed] = res; // 3. 将更新后的对象重新存入ReactiveVar instance.test.set(currentData); } }); }); });
2. 展示值(模板helper中)
Template.yourTemplateName.helpers({ getTestValue(parameterPassed) { // 先获取整个对象,再通过key取对应值,加个默认值避免undefined return Template.instance().test.get()[parameterPassed] || '暂无数据'; } });
3. 模板中调用helper
<template name="yourTemplateName"> {{#each usms}} <div>ID: {{this}},对应值: {{getTestValue this}}</div> {{/each}} </template>
额外说明
- 如果你的
parameterPassed不是直接来自usm,记得调整对应变量的取值逻辑。 - 因为Meteor.call是异步的,初始时ReactiveVar是空对象,所以helper里加个默认值会更友好,避免页面显示
undefined。
内容的提问来源于stack exchange,提问作者N G
相关产品推荐
相关产品推荐

