aurora-article icon indicating copy to clipboard operation
aurora-article copied to clipboard

angular实现一些vue功能

Open starryiu opened this issue 3 years ago • 0 comments

angular用了一阵了,之前在一直用vue,在初次使用时觉得有些不方便,比如vue中的计算属性,属性监听、keep-alive标签等,这里说明一下我的解决方法。

补充

已经有大佬做了更全面的总结了,Component Party

实现类似于 vue 中的计算属性和属性监听

这个功能可以用 rxjs 来实现,当然也可以简单的写个函数即可。

  articles = [];
  //articleLength 是一个计算属性
  get articleLength() {
    return this.arr.length;
  }
  changeArticles(value) {
    //需要监听时使用 changeArticles 函数,不需要监听时直接修改 articles 属性即可
    this.articles = value;
    this.watchArticles(this.articles, value);
  }
  //watch 监听
  watchArticles(oldValue, newValue) {
    console.log(oldValue, newValue);
  }

新方式!!!现在 angular 新推出了 signal(信号),更加简单,详情

实现 v-else-if

这个可以使用 ngswitch 指令来实现。

<div [ngSwitch]="theme">
  <div *ngSwitchCase="'touhu'">
    <h1>touhu 对应的内容</h1>
  </div>
  <div *ngSwitchCase="'school'">
    <h1>school 对应的内容</h1>
  </div>
</div>

实现 keep-alive 功能

keep-alive 可以实现多个组件间动态切换时缓存被移除的组件实例,angular本身并不支持缓存组件,不过可以使用服务+rxjs来实现缓存数据来解决这个问题,这有点像 vue2 的 vuex 或 vue3 的 pinia。

  /**
   *  缓存一个全局的count变量
   *  在组件中通过订阅myCount$获取,通过change函数更改
   */
  private myCount = new BehaviorSubject(0);
  myCount$ = this.myCount.asObservable();
  changeMyCountSource(value: number) {
    this.myCount.next(value);
  }

模板引用

angular 使用模板引用需要在标签上 #自定义名 来声明

// html
<p #segment>{{theme}}</p>
<button (click)="changTheme(segment)">按钮</button>

// js
changTheme(segment:HTMLParagraphElement){
  this.theme = this.theme ==='touhu' ?'school':'touhu'
  console.log(segment.innerText)
}

关于 angular

个人并不推荐学习 angular ,中文资料实在太少了, angular 视频教程也非常少,b站也都是一些浅浅的毛皮,建议学习 vue 或者 react,尤其是 vue,学起来简单,国产插件多,用起来省心。

starryiu avatar Sep 17 '22 10:09 starryiu