【问题标题】:Conditionally display Element using Aurelia使用 Aurelia 有条件地显示 Element
【发布时间】:2016-05-16 13:51:06
【问题描述】:

所以我将auth 类注入到我的main.js

import {Auth} from 'auth';
import {inject} from 'aurelia-framework';

@inject(Auth)
export class App {
    constructor(auth) {
        this.auth = auth;
    }

    get isLoggedIn() { return this.auth.isLoggedIn; }
}

所以在我的app.html

<form>
    <!-- form login elements -->
</form>

如何根据我的应用 getter 函数有条件地显示此元素。

【问题讨论】:

标签: javascript ecmascript-6 aurelia


【解决方案1】:

您可以使用 if.bind 有条件地绑定您的 DOM 元素。

 <form>
      <div if.bind="auth.isLoggedIn">
        <!--this DOM element will be bind only if auth.isLoggedIn is true-->
      </div>
 </form>

您也可以选择使用 show.bind ,但这只会隐藏您的 DOM 元素。 if.bind 不会在您的页面上呈现它。

【讨论】:

【解决方案2】:

如果您需要在不满足条件时从标记中完全删除元素,您可以使用if.bind(正如@Pratik Gajjar 回答的那样):

<template>
  <div if.bind="auth.isLoggedIn">
    <!--this DOM element will be bind only if auth.isLoggedIn is true-->
  </div>
</template>

如果需要在元素上有条件地设置display: none,可以使用show.bind

<template>
  <div show.bind="auth.isLoggedIn">
    <!--this DOM element will be shown only if auth.isLoggedIn is true-->
  </div>
</template>

详情请看http://aurelia.io/hub.html#/doc/article/aurelia/framework/latest/cheat-sheet/6

【讨论】:

    【解决方案3】:

    所以我创建了一个值转换器:

    export class CssdisplayValueConverter {
        toView(value) {
            return value ? 'none' : 'display';
        }
    }
    

    然后在我的 app.html 中:

    <require from='css-display'></require>
    
    <form css="display: ${isLoggedIn() | cssdisplay}"></form>
    

    砰,完成。

    【讨论】:

    • 值得向遇到此问题和此答案的其他人特别指出:您可以只使用show.bind 而不是上述值转换​​器。它有效地做同样的事情,并且在 Aurelia 中开箱即用。 &lt;form show.bind="!isLoggedIn"&gt;&lt;/form&gt;
    • 当 Aurelia 内置了这个功能时,使用值转换器是没有意义的。
    • 好吧,当你从测试版中使用时:)
    【解决方案4】:

    您可以使用if.bindshow.bind 通过检查条件来绑定元素

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-19
      • 1970-01-01
      • 2015-03-19
      • 2012-02-01
      • 2016-01-01
      • 1970-01-01
      相关资源
      最近更新 更多