我尝试了几种不同的方法,它们的行为方式相同(请参阅下面的代码)。我使用空格键 if 条件(并尝试使用帮助程序)来检查用户是否已登录,然后显示登录/注册链接(如果未登录)。如果是,请将其隐藏。
我注意到,在初始页面加载时(如果他们从不同的站点导航回来),登录/注册链接在隐藏之前会快速显示(如果用户仍然登录)。有没有办法确保如果条件为假,视图中不会呈现任何元素?在我看来,它应该在视图开始渲染之前进行检查,然后在页面上显示适当的元素。
谢谢您的帮助! -克里斯
我遇到的闪烁的解决方案:我正在检查用户,尽管视图的渲染速度比数据库查询更快。我添加了一个防护表达式(见下文),这似乎可以解决闪烁问题。
isUserLoggedOut: function() {
var user = Meteor.user();
if(Meteor.user()) {
return user && false;
} else{
return user && true;
}
}
尝试#1:
Template.headerTpl.helpers({
isUserLoggedIn: function() {
var user = Meteor.user();
if(user) {
return false;
} else{
return true;
}
}
});
<template name="headerTpl">
{{#if isUserLoggedIn}}
<li style="display:none;"><a href="{{pathFor 'userRegistrationFormTpl'}}" id="signup-js">Sign Up</a></li>
<li><a href="{{pathFor 'userLoginFormTpl'}}" id="login-js">Login</a></li>
{{/if}}
</template>
尝试#2:
Template.headerTpl.helpers({
isUserLoggedIn: function() {
var user = Meteor.user();
if(user) {
return "hide";
} else{
return "show";
}
}
});
<template name="headerTpl">
<li class={{isUserLoggedIn}}><a href="{{pathFor 'userRegistrationFormTpl'}}" id="signup-js">Sign Up</a></li>
<li class={{isUserLoggedIn}}><a href="{{pathFor 'userLoginFormTpl'}}" id="login-js">Login</a></li>
</template>
尝试#3:
{{#if currentUser}}
{{else}}
<li style="display:none;"><a href="{{pathFor 'userRegistrationFormTpl'}}" id="signup-js">Sign Up</a></li>
<li><a href="{{pathFor 'userLoginFormTpl'}}" id="login-js">Login</a></li>
{{/if}}
尝试#4:
<template name="headerTpl">
{{#if isUserLoggedOut}}
{{> signInLinksTpl}}
{{/if}}
</template>
<template name="signInLinksTpl">
<li style="display:none;"><a href="{{pathFor 'userRegistrationFormTpl'}}" id="signup-js">Sign Up</a></li>
<li><a href="{{pathFor 'userLoginFormTpl'}}" id="login-js">Login</a></li>
</template>
Template.headerTpl.helpers({
isUserLoggedOut: function() {
if(Meteor.user()) {
return false;
} else{
return true;
}
}
});