自定义元素(组件)- 含有ViewModel的自定义组件
.ts文件
1.首先我们要引入两个依赖!customElement和bindable。
2.下面这个例子还示意了如何给自定义组件绑定属性to,我们使用@bindable来绑定。
3.我们在这里用@customElement(“say-hello”)来定义这个自定义组件的名字,也是我们在使用这个自定义组件的时候的标签名。
import {customElement, bindable} from 'aurelia-framework';
@customElement('say-hello')
export class SayHello {
@bindable to: string;
speak(): void {
alert(`Hello ${this.to}!`);
}
}
.html文件
<template>
<button click.trigger="speak()">Say Hello To ${to}</button>
</template>
Custom Element Use
- input里面有一个属性ref=“name”,然后我们在下面的组件用了这个name.value,我们之所以用ref这个属性,是为了方便在有些时候方便的拿到html的DOM。
- 在需要使用say-hello这个自定义组件的时候,我们需要在使用它的组件内require这个自定义组件。
<template>
<require from="say-hello"></require>
<input type="text" ref="name">
<say-hello to.bind="name.value"></say-hello>
</template>
自定义元素(组件)- 不含有ViewModel的自定义组件
Declare Custom Element Without View-Model With Binding Copy
HTML
<template bindable="greeting,name">
Say ${greeting} To ${name}
</template>
Add Global Custom Element Without View-Model Copy
TypeScript
- 要将这个不含有VM的html文件加入globalResources()方法中
.ts
aurelia.use.globalResources('./js-less-component.html');
使用这个自定义组件
2. 我们首先还是要引入这个html文件才可以使用。
3. 这个html文件名就是我们使用组件标签时候的标签名。
<require from="./js-less-component.html"></require>
<js-less-component greeting="Hello" name.bind="someProperty"></js-less-component>
自定义组件变量绑定
- 当绑定变量到组件上时,在自定义组件的VM里面,我们用驼峰原则定义变量,但是如果在其他html 文件里面我们要使用我们的自定义组件,我们用中间放一个破折号的形式使用我们的自定义组件名,这个破折号的自定义组件名字,是需要我们用@customElement(“say-hello”)定义的
自定义组件的ViewModel
import {bindable} from 'aurelia-framework';
@customElement("say-hello");
export class SayHello {
@bindable to: string;
@bindable greetingCallback: Function;
speak(): void {
this.greetingCallback(`Hello ${this.to}!`);
}
}
自定义组件的使用 .html
<template>
<require from="./say-hello"></require>
<input type="text" ref="name">
<say-hello to.bind="name.value" greeting-callback.call="doSomething($event)"></say-hello>
</template>
自定义组件的其他方法
查看官网: http://aurelia.io/hub.html#/doc/article/aurelia/framework/latest/cheat-sheet/9