0

所以我有一个简单的服务器文件:

import { Meteor } from 'meteor/meteor';

const Animals = new Mongo.Collection("animals");

let animalsFindOne = Targets.findOne({animal: "henry"});
console.log(_.get(animalsFindOne, 'food.favorite.amount'));

以及animals.js呈现给模板的文件

import {Template} from "meteor/templating";
import {Mongo} from "meteor/mongo";

import "/imports/ui/targets/animals.html";

const Animals = new Mongo.Collection("animals");
let animalsFindOne = Targets.findOne({animal: "henry"});

Template.targets.helpers({
    foodAmount: function() {
        return _.get(animalsFindOne, 'food.favorite.amount';
    }
});

我可以将“foo”作为 foodAmount 返回,并且模板会将其渲染得非常好。对于_.get我使用erasaur:meteor-lodash,它在server.js. 在服务器控制台中,输出为“5”,这是预期的输出并且很棒。
我在这里缺少什么?
编辑:我也安装了自动发布,我不期待删除它,因为这个软件无论如何都是一个测试。

4

1 回答 1

1

animalsFindOne已经在助手外部定义,foodAmount因此它不会触发模板的基于反应性的重绘机制。

为了在助手中获得反应,您需要在助手中调用查询:

import {Template} from "meteor/templating";
import {Mongo} from "meteor/mongo";

import "/imports/ui/targets/animals.html";

const Animals = new Mongo.Collection("animals");


Template.targets.helpers({
    foodAmount: function() {
        let animalsFindOne = Targets.findOne({animal: "henry"});
        return _.get(animalsFindOne, 'food.favorite.amount';
    }
});

编辑:Meteor 允许与更新版本的可选链接,所以这里不需要 lodash:

Template.targets.helpers({
    foodAmount: function() {
        let animalsFindOne = Targets.findOne({animal: "henry"});
        return animalsFindOne?.food?.favorite?.amount
    }
});
于 2021-01-11T14:52:15.870 回答