Aurelia - 根据功能结果隐藏/显示Div

Gal*_*tun 1 javascript aurelia

使用Aurelia,我正在寻找与Angular 1类似的行为,我可以在其中使用函数ng-show.如:

<div ng-show='isShown()'></div>
Run Code Online (Sandbox Code Playgroud)

这是我想要做的一个例子:

app.js

export class App {
    this.options = ['opt1', 'opt2', 'opt3', 'opt4, 'opt5'];
    this.current = "";
    isShown() {
        return (this.current === 'opt1');
    }
}
Run Code Online (Sandbox Code Playgroud)

app.html

<select value.bind="current">
    <option repeat.for="opt of options" model.bind="opt">${opt}</option>
</select>

<div if.bind="isShown()">...</div>
Run Code Online (Sandbox Code Playgroud)

如果初始值为opt1,则显示div,但在选择更改时不显示/隐藏.我能让这个工作的唯一方法是这样做:

<div if.bind="current === 'opt1'"></div>
Run Code Online (Sandbox Code Playgroud)

在这种情况下这也不错,但是我希望能做到这样的事情,我认为在JS中使用函数而不是在标记中可以更好地工作:

<div if.bind="current === 'opt1' || current === 'opt2' || current === 'opt3'"></div>
Run Code Online (Sandbox Code Playgroud)

提前致谢!

小智 7

一种方法是让你的函数成为一个吸气剂:

get isShown() {
    return (this.current === 'opt1');
}
Run Code Online (Sandbox Code Playgroud)

和:

<div if.bind="isShown">Show/Hide</div>
Run Code Online (Sandbox Code Playgroud)

但是这样它会被脏检查,以避免你可以使用computedFrom:

import { computedFrom } from 'aurelia-framework';

export class App {

    constructor() {
        this.options = ['opt1', 'opt2', 'opt3', 'opt4', 'opt5'];
        this.current = '';
    }

    @computedFrom('current')
    get isShown() {
        return (this.current === 'opt1');
    }

}
Run Code Online (Sandbox Code Playgroud)

你也可以使用@observable:

import { observable } from 'aurelia-framework';

export class App {

    isShown = false;
    @observable current = '';

    currentChanged(newValue, oldValue) {
        this.isShown = (newValue === 'opt1');
    }

}
Run Code Online (Sandbox Code Playgroud)

你也可以使用BindingEngine:

import { BindingEngine, inject } from 'aurelia-framework';

@inject(BindingEngine)
export class App {

    isShown = false;
    current = '';
    options = ['opt1', 'opt2', 'opt3', 'opt4', 'opt5'];

    constructor(bindingEngine) {
        this.bindingEngine = bindingEngine;

        this.bindingEngine
            .propertyObserver(this, 'current')
            .subscribe(this.currentChanged.bind(this));
    }

    currentChanged(newValue, oldValue) {
        this.isShown = (newValue === 'opt1');
    }
}
Run Code Online (Sandbox Code Playgroud)