流星助手不设置数据



我需要在模板 onRender 钩子中获取图像数组,然后在帮助程序中获取这些图像以创建滑块。此滑块应在模式打开时创建。但是当我运行此代码时,助手不会向模板发送任何数据。在控制台.log(我可以看到这个数组(。 我有这个代码:

Template.slider.onRendered(function() {
this.autorun(()=> {
let mainImg = this.data.mainImage || null;
let imgs = this.data.images || [];
this.data.imgSet = Images
.find({_id: { $in: [mainImg, ...imgs] }})
.map(img => img.url());
});
});

和助手:

Template.slider.helpers({
images() {
let imgSet = this.imgSet;
if(imgSet) {
const slider = $('#vertical').lightSlider({
gallery: true
});
return this.imgSet;
}
return [];
}
});

我的模板文件:

<ul id="vertical" class="light_slider">
{{#each images}}
<li data-thumb="{{this}}">
<img src="{{this}}" style="height:100%"/>
</li>
{{/each}}
</ul>

您的帮助程序不依赖于任何反应变量,这就是为什么无论您的imgSet变量更新如何,它都只工作一次。

为了得到你想要的东西,你必须制作反应变量并更新它。

像这样:

Template.slider.onRendered(function() {
this.imgSet = new ReactiveVar([]);
this.autorun(()=> {
const mainImg = this.data.mainImage || null;
const imgs = this.data.images || [];
const imgSet = Images
.find({_id: { $in: [mainImg, ...imgs] }})
.map(img => img.url());
this.imgSet.set(imgSet);
});
});
Template.slider.helpers({
images() {
const imgSet = Template.instance().imgSet.get();
if(imgSet) {
// let's give render the time to rerender
// though I'd recommend to put that into onRendered
Meteor.setTimeout(() => {
$('#vertical').lightSlider({
gallery: true
});
}, 50);
return imgSet;
}
return [];
}
});

最新更新