gpt4 book ai didi

javascript - Aurelia - 根据函数结果隐藏/显示 Div

转载 作者:行者123 更新时间:2023-11-30 07:33:43 26 4
gpt4 key购买 nike

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

<div ng-show='isShown()'></div>

这是我正在尝试做的一个例子:

app.js

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

app.html

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

<div if.bind="isShown()">...</div>

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

<div if.bind="current === 'opt1'"></div>

在这种情况下这还不错,但我希望做这样的事情,我觉得在 JS 中而不是在标记中使用函数会更好:

<div if.bind="current === 'opt1' || current === 'opt2' || current === 'opt3'"></div>

提前致谢!

最佳答案

一种方法是使您的函数成为 setter/getter :

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

和:

<div if.bind="isShown">Show/Hide</div>

但是这样它会被脏检查,以避免你可以使用 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');
}

}

你也可以使用@observable:

import { observable } from 'aurelia-framework';

export class App {

isShown = false;
@observable current = '';

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

}

您还可以使用 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');
}
}

关于javascript - Aurelia - 根据函数结果隐藏/显示 Div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41562070/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com