如何把一个vue组件改为ionic/angular组件?

同是mvvm框架,他们之间是很相似的,如何你已经熟悉其中的一个,那么另一个也就基本上也就会的差不多了。

一、动态属性、值、事件绑定

vue中使用v-bind:或者之间分号:进行绑定

ng中左括号[]进行绑定

v-model –--->[(ngModel)]

@click ---->(click)

二、条件判断

v-if----->*ngIf

三、显示隐藏

v-show------> [hidden]

四、遍历一组数组进行渲染

v-for="item in items" -----> *ngFor="let item of items"
v-for="(item ,index)in items" -----> *ngFor="let item of dots; index as i"
。。。。

父子组件如何传值

1.父组件传值到子组件

<app-header [msg]="msg"></app-header>

2. 子组件接受父组件的值

子组件里面通过 @Input 接收父组件传过来的数(需要先引入input模块)--相当于vue的props

3.子组件主动发送数据给父组件

引入Output,EventEmitter

import {Output,EventEmitter} from "@angular/core";

@Output() private childOuter = new EventEmitter();// 子组件主动发送数据this.childOuter.emit("我是子组件的数据");

4.在父组件中接收数据

// childOuter即是子组件发送的outer(类似Android中的广播)

<app-index (childOuter)="getData($event)"></app-index> // ts文件中: getData(msg:string) { console.log(msg);// 接收到的数据 }

------相当于vue的子组件派发事件到父组件

5.父组件主动调用子组件

方法1

// 引用子组件 
<app-index #index></app-index> // 使用子组件中的方法
<button (click)="index.childRun()">调用index中的方法</button>

方法2

也可以在ts文件中调用:

// 引用子组件 html文件

<app-index #index></app-index> <button (click)="parentClick(index)">调用index中的方法</button>

// ts 文件

parentClick(obj) { obj.childRun(); }

方法3

ViewChild主动获取数据相当于vue 父组件里面对子组件加ref引用找到子组件调用其方法

ViewChild 是属性装饰器,用来从模板视图中获取匹配的元素

页面上#xx ts中@ViewChild(xx)

获取匹配的组件也可以是元素,

组件直接导入 @ViewChild(组件名)

元素页面上加#xx @ViewChild(xx)

参考 http://oomusou.io/angular/viewchild/

子组件里面监听父组件传递过来值的变化

onChanges钩子使用 相当于vue里面的watch

……

ionic/ng常用代码片段

[src]="base64Image"

//是否存在

[hidden]="lastImage === null"

//是否禁用

[disabled]="lastImage === null"

//文案显示互斥

{{isFavourite ? '取消关注' : '关注'}}

//元素显示互斥

*ngIf="!isSelf" 渲染与否,切换的时候回重新渲染

如何已经有了class再追加class 而不是替换class

<span class="dot" [ngClass]="{active: currentPageIndex === i }" *ngFor="let item of dots; index as i"></span>

替换class

<span class="dot" [class]="{active: currentPageIndex === i }

或者 [hidden]=”!isSelf” 不重新渲染只显示隐藏 注意与v-show相反等同于

v-show=’isSelf’

Class显示互斥

<span [ngClass]="{'active':sex===1}" (click)="switchSex(1)"></span><b (click)="switchSex(1)">男</b>

<span [ngClass]="{'active':sex===0}" (click)="switchSex(0)"></span><b (click)="switchSex(0)">女</b>

根据布尔值绑定某一属性

[color]="btnDisable===true?'light':''"

注意不能带花括号

下面2种都是不对的

<button ion-button block [color]="{btnDisable===true?'light':''}">下一步</button>

<button ion-button block [color]="{'light':btnDisable===true}">下一步</button>