angular,vue,react的基本語法—雙向資料繫結、條件渲染、列表渲染、angular小案例
阿新 • • 發佈:2018-12-06
基本語法:
1、雙向資料繫結
vue
指令:v-model="msg"
react
constructor(){ this.state{ msg:"雙向資料繫結" } render(){ <input type="text" value={this.state.msg} onChange={(ev)=>this.handleChange(ev)} />{msg} } handleChange(ev){ this.setState({ msg:ev.target.value }) }
angular --ngMel(屬性型指令)
app.Module.ts: import FromsModule from "@angular/froms"; app.component.ts: export class Appcomponent{ msg:"雙向資料繫結" } app.components.html: <input [(ngModel)]="msg" />{{msg}}
2、條件渲染:
vue
指令: v-if v-else-if v-else v-show
react
使用三目(三聯)運算:{true ? x:y}
angular ---*ngIf(結構型指令)
指令:*ngIf 沒有else指令 如果想要else,要使用ng-template
demo: <div *ngIf="isShow else elseBack">aaaaaaaaaaaaaaaaaaa</div> <ng-template #elseBack>ddddddddddddddd</ng-template> ng-template:模板
3、列表渲染:
vue
指令:v-for <li v-for="item,index in list" key="index">{{item}}</li>
react
this.state.list.map((item)=>{ return <li key="item.id">{item}</li> })
angular
指令:*ngFor
<ul>
<li *ngFor="let item of list,let i=index">{{i}},{{item}}</li>
</ul>
<ul>
<li *ngFor="let item of list,index as i">{{i}},{{item}}</li>
</ul>
angular小案例:Todos
app.component.html: <input type="text" [(ngModel)]="info" (keydown)="handleAdd($event)" > //輸入框 <ul> <li *ngFor="let item of list,index as i"> {{i}},{{item}} <button (click)="handleRemove(i)">X</button> </li> //顯示列表 </ul> app.component.ts: export class AppComponent { list:Array<any>=[111,222,333]; //加入資料的陣列 info=""; //資料繫結變數 handleAdd(ev){ //新增資料的方法 if(ev.keyCode===13) { this.list.unshift(this.info); this.info = ""; } } handleRemove(index){ //刪除資料的方法 this.list.splice(index,1); } }