wil*_*emx 9 meteor iron-router
如何制作Iron:路由器重新渲染模板?
我有这个HTML:
<head>
</head>
<body>
</body>
<template name="mainLayout">
<a href="{{pathFor route='list'}}">list</a>
<a href="{{pathFor route='find' query='q=xxx'}}">find</a>
{{> yield}}
</template>
<template name="listTemplate">
<p>list</p>
</template>
Run Code Online (Sandbox Code Playgroud)
这个js:
Router.configure({
layoutTemplate: 'mainLayout'
});
Router.route('/list', {
name: 'list',
template: 'listTemplate'
});
Router.route('/find', {
name: 'find',
template: 'listTemplate',
data: function () {
return this.params.query;
}
});
if (Meteor.isClient) {
Template.listTemplate.rendered = function () {
if (this.data)
console.log('find ' + this.data.q);
else
console.log('list all');
};
}
Run Code Online (Sandbox Code Playgroud)
当我单击链接切换视图(使用console.log模拟此处)时,路径确实会更改,但模板不会重新呈现.有没有办法强迫铁:路由器重新渲染?
小智 1
你可以尝试这样的事情:
Router.configure({
layoutTemplate: 'mainLayout'
});
Router.route('/list', {
name: 'list',
template: 'listTemplate',
action: function() {
this.state.set('query', this.params.query);
}
});
Router.route('/find', {
name: 'find',
template: 'listTemplate',
data: function() {
return this.params.query;
},
action: function() {
this.state.set('query', this.params.query);
}
});
if (Meteor.isClient) {
Template.listTemplate.rendered = function() {
this.autorun(
function() {
if (this.state.get('query'))
console.log('find ' + this.data.q);
else
console.log('list all');
}
);
};
}
Run Code Online (Sandbox Code Playgroud)
呈现的方法不是反应性的,这就是您需要自动运行的原因。模板“this.data”不是响应式的,因此您需要一个响应式变量来执行此操作,可以是会话变量、控制器状态或某种响应式变量。
您可能需要添加reactive-var 包,具体取决于您采用的方法。