Meteor Spacebars {{#if someCondition}} 在页面刷新时简要显示数据

2023-11-30

我尝试了几种不同的方法,它们的行为方式相同(请参阅下面的代码)。我使用空格键 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;
    }
  }
});

您需要订阅 Meteor.users 集合,模板将在 Meteor.user() 创建后呈现,如果您不等待订阅页面将闪烁,因为开始时 Meteor.users 集合中没有任何内容。

您可以在具有登录字段的模板上使用新的 Meteor 功能

Template.login.onCreated(function () {
  var self = this;

  self.autorun(function () {
    self.subscribe("users");
  });
});

在 HTML 中

{{#if Template.subscriptionsReady}}
    <!--content-->
{{else}}
    Give me a second...
{{/if}}

当然,您需要创建名为“用户”的发布

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Meteor Spacebars {{#if someCondition}} 在页面刷新时简要显示数据 的相关文章

随机推荐