我想在我的模板onCreated方法中初始化ReactiveVar并将其传递给帮助者:
import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';
import './record-infos-page.html';
import './record-infos-page.scss';
Template.Record_infos_page.onCreated(function recordInfosPageOnCreated() {
this.checkedVariablesIds = new ReactiveVar(['HkcEjZjdxbobbNCZc', 'uTmJKTfoWFFfXPMwx']);
console.log(1, this.checkedVariablesIds.get());
});
Template.Record_infos_page.helpers({
checkedVariablesIds() {
const vars = Template.instance().checkedVariablesIds.get();
console.log(2, vars);
return vars;
},
});
console.log结果是:
1 ['HkcEjZjdxbobbNCZc', 'uTmJKTfoWFFfXPMwx']
2 undefined
为什么我在助手中有未定义?
谢谢!
答案 0 :(得分:2)
您可以使用instance.autorun
来反复获取模板中变量的更改:
您可以使用onCreated或onRendered回调中的this.autorun 反应性地更新DOM或模板实例。
import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';
import './record-infos-page.html';
import './record-infos-page.scss';
Template.Record_infos_page.onCreated(function() {
const instance = this;
instance.autorun(function() {
if (!instance.checkedVariablesIds) {
instance.checkedVariablesIds = new ReactiveVar(['HkcEjZjdxbobbNCZc', 'uTmJKTfoWFFfXPMwx']);
console.log(1, instance.checkedVariablesIds.get());
}
});
});
Template.Record_infos_page.helpers({
checkedVariablesIds() {
const vars = Template.instance().checkedVariablesIds.get();
console.log(2, vars);
return vars;
},
});