如何在 meteor 上使用URL参数。
该URL可能看起来像这样:http://my-meteor.example.com:3000?task_name=abcd1234
我想在 meteor 应用程序的mongodb查询中使用'task_name'(abcd1234)。
例如。
Template.task_app.tasks = function () {
return Tasks.find({task_name: task_name});
};
谢谢。
最佳答案
您可能会想要使用路由器来照顾路径并为不同的路径渲染某些模板。铁路由器套件是最好的一种。如果您尚未使用它,我强烈建议您使用。
使用Iron-Router后,获取查询字符串和url参数变得非常简单。您可以在此处查看文档部分:https://github.com/iron-meteor/iron-router/blob/devel/Guide.md#route-parameters
对于您给出的示例,路线如下所示:
Router.map(function () {
this.route('home', {
path: '/',
template: 'task_app'
data: function () {
// the data function is an example where this.params is available
// we can access params using this.params
// see the below paths that would match this route
var params = this.params;
// we can access query string params using this.params.query
var queryStringParams = this.params.query;
// query params are added to the 'query' object on this.params.
// given a browser path of: '/?task_name=abcd1234
// this.params.query.task_name => 'abcd1234'
return Tasks.findOne({task_name: this.params.query.task_name});
}
});
});
这将创建一条路由,该路由将使用与任务名称匹配的第一个任务的数据上下文来呈现“task_app”模板。
您还可以使用Router.current()从模板助手或其他函数访问url参数和其他路由信息,以获取当前路由。因此,例如在助手中,您可以使用
Router.current().params.query.task_name
获取当前任务名称。 Router.current()是一个 react 性元素,因此,如果在 react 性计算中使用它,则当对路由进行任何更改时,计算将重新运行。
关于meteor - 如何使用Meteorjs使用URL参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22120489/