创建具有可绑定属性的自定义元素非常简单。如果要创建一个接受一个或多个插件可以使用的值的元素,则需要使用@bindable装饰器和语法。
在下面,我们正在创建一个自定义元素,该元素接受一系列水果并显示它们。
示例: my-element.js
import {bindable} from 'aurelia-framework';
const validFruits = [
'Apple',
'Banana',
'Orange',
'Pineapple',
'Grapes',
'Peach',
'Plum',
'Dates',
'Strawberries'
];
export class FruitCustomElement {
@bindable fruits = [];
fruitsChanged(newVal, oldVal) {
if (newVal) {
newVal.filter(fruit => {
return validFruits.indexOf(fruit) >= 0;
});
}
}
}<template>
<ul if.bind="fruits">
<li repeat.for="fruit of fruits">${fruit}</li>
</ul>
</template>使用它:
export class MyViewModel {
myFruits = [];
attached() {
this.myFruits= ['Apple', 'Banana', 'Orange', 'Pineapple', 'Grapes', 'Peach'];
}
}<template> <require from="./my-element"></require> <fruit fruits.bind="myFruits"></fruit> </template>