
基于vue3速学angular
代码核心部分是ts文件里面的@Component,这里的功能是抛出了当前这个组件的调用名称 并且导入了html 和 css文件。参考:https://zhuanlan.zhihu.com/p/546843290?@click=>(click)注意,vue里面可以隐藏函数的括号,angular必须加。2.html写法上,可以看到angular写法里面有很多括号[] (),那具体是干什么用的呢。可以很
因为工作原因,需要接手新的项目,新的项目是angular框架的,自学下和vue3的区别,写篇博客记录下:
参考:https://zhuanlan.zhihu.com/p/546843290?utm_id=0
1.结构上:
vue3:一个vue文件,包括了html ts css
angular:至少需要三个文件,分别写html ts css
文件写法如下:XXXXX.component.html
代码核心部分是ts文件里面的@Component,这里的功能是抛出了当前这个组件的调用名称 并且导入了html 和 css文件
@Component({
// 组件标签名称 调用名称
selector: 'xxxx-target',
// 模板页面路径
templateUrl: './xxxx-target.component.html',
// 样式文件路径
styleUrls: ['./xxxx-target.component.less']
})
2.html写法上,可以看到angular写法里面有很多括号[] (),那具体是干什么用的呢
vue写法
<button v-if="isShow" class="test-button" @click="onClick" :title="buttonTitle">{{ '1111' }}</button>
<input v-else type="text" v-model="name" />
<div v-for="(item,index) in cardList"></div>
<div v-show="isShow"></div>
<div :class="{ 'disabled': disabled, 'un-hover': true}" :style="{ color: color }"></div>
<div> <slot></slot> <slot name="icon"></slot> </div>
<input v-if="isShow" type="text" v-model="name" />
<input v-else type="text" v-model="name" />
angular写法
<button *ngIf="isShow" class="test-button" (click)="onClick()" [title]="buttonTitle">{{ '1111' }}</button>
<input #elseTemplate type="text" [(ngModel)]="name" />
<div *ngFor="let item of cardList;let i = index"></div>
<div [hidden]="isShow"></div>
<div [ngClass]="{ 'disabled': disabled, 'un-hover': true}" [ngStyle]="{ color: color }"></div>
<div> <ng-content></ng-content> <ng-content select="[icon]"></ng-content> </div>
<input *ngIf="isShow; else btnView" type="text" [(ngModel)]="name" />
<input #btnView type="text" [(ngModel)]="name" />
可以很轻松的看出差异
@click=>(click) 注意,vue里面可以隐藏函数的括号,angular必须加
:title=>[title]
v-model=>[(ngModel)]
v-if=>ngIf
v-else=>#elseTemplate
或者ngIf=“isShow; else btnView” #btnView,else的部分自定义,下面用#XXX来引用
v-for=>*ngFor 注意,angular的index需要let i = index写,然后下面用i来当index用
v-show=>[hidden]
:class=>[ngClass]
:style=>[ngStyle]
slot=>ng-content 注意,angular的插槽用的是select=“[xxx]”
插槽使用方式区别
<div-xxx>
<template #icon>
<div class="tips">
</div>
</template>
</div-xxx>
差别就是angular不需要套一层template,如果是icon插槽增加一个icon属性即可
<div-xxx>
<div icon>
<div class="tips">
</div>
</div>
</div-xxx>
3.ts写法上:
先来几个最常用的,子和父如何通讯的
angular:
在Angular组件之间共享数据,有以下几种方式:
1. 父组件至子组件: 通过 @Input 共享数据
2. 子组件至父组件: 通过 @Output EventEmitter 共享数据
3. 子组件至父组件: 通过 本地变量共享数据
4. 子组件至父组件: 通过 @ViewChild 共享数据
5. 不相关组件: 通过 service 共享数据,
缓存、广播等
下面用代码看下和vue3的区别
vue3写法
子组件:
<template>
<button @click="onClick" loading="loading"
{{ $t('refresh') }}
</button>
</template>
<script lang="ts" setup>
const emit = defineEmits(['on-click']);
const props = defineProps({
loading: { type: Boolean, default: true },
});
const onClick = () => {
emit('on-click');
};
</script>
父组件:
<template>
<button-XXXX @onClick="onRefresh" :loading="xxxLoading"/>
</template>
<script lang="ts" setup>
const xxxLoading= ref(false);
const onRefresh= async() => {
xxxLoading.value=true;
// 执行函数
await XXX();
xxxLoading.value=false;
};
</script>
angular写法:
子组件:
@Component({
selector: 'xxx-button',
template: `<button (click)="onClick(true)">{{buttonName}}</button>`,
})
export class xxxComponent implements OnInit{
@Output() vote = new EventEmitter<any>();
@Input() buttonName: any;
constructor() {}
ngOnInit(): void {
}
onClick(isAdd:boolean): void {
this.vote.emit(isAdd);
}
}
父组件:
@Component({
selector: 'xxx-div',
template: `<xxx-button [buttonName]="buttonName" (vote)="onVote($event)"></xxx-button>`,
})
export class xxxComponent {
buttonName="按钮名称";
constructor() {}
onVote(isAdd:boolean): void {
if(isAdd){
//具体操作
}
}
}
那么vue里面的父通过ref访问子组件,在angular要怎么实现呢,如下,只需要在父组件ts代码里面写@ViewChild(‘xxx’) xxx ,然后在html子组件里面加上#xxx就行
@Component({
selector: 'xxx-div',
template: `<xxx-button #test1 [buttonName]="buttonName" (vote)="onVote($event)"></xxx-button>`,
})
export class xxxComponent {
@ViewChild('test1') test1;
buttonName="按钮名称";
constructor() {}
onVote(isAdd:boolean): void {
if(isAdd){
//具体操作
console.log('test1',test1)
}
}
}
2024年5月29日15:29:58:
发现angular除了ViewChild,还有个ViewChildren,二者有啥区别呢?
ViewChild:用于获取组件模板上的元素
ViewChildren:与ViewChild类似,不同的是,它可以批量获取模板上相同选择器的元素,并存放到QueryList类中。
下面打个log看看分别输出什么
<div #test2></div>
@ViewChild('test2') test2;
//@ViewChildren('test2') test2;
ngAfterViewInit() {
console.log('ViewChild.test2', this.test2);
}
可以很明显的看到,其实就是字面含义,一个输出一个孩子,一个输出一群孩子
,那么平时应该都用ViewChild比较多
监听事件:
vue3里面有watch watcheffet,我研究了下angular的,好像只有类似watcheffet的监听方法
需要监听的参数写在ngOnChanges里面的changes.XXX 当这个值变化的时候会触发
vue3写法
watch(
() => props.isOpen,
(value) => {
console.log(value)
},
{ deep: true, immediate: true }
);
watchEffect(() => {
visible.value = props.show;
});
angular写法
@Input() xxxDeatail;
ngOnChanges(changes: SimpleChanges): void {
// xxxDeatail 属性值变更时
if (changes.xxxDeatail) {
this.initDeatail();
}
}
initDeatail(){
}
计算属性
angular好像没有这玩意,只有个@pipe管道的东西,相当于写一个公共方法,用用挺麻烦,比如计算时间展示,或者复杂数据,重复操作的时候可以用到,感兴趣可以搜下
下面是个简单demo 主要看下用法,很多代码都省略了
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'boolToString',
})
export class BoolToStringPipe implements PipeTransform {
transform(value: boolean, trueValue: string, falseValue: string): unknown {
return value ? trueValue : falseValue;
}
}
用的时候:
import { BoolToStringPipe } from 'boolToString.pipe';
@Component({
providers: [BoolToStringPipe ],
})
export class PatchUpgradeComponent implements OnInit {
constructor(
private boolToStringPipe : BoolToStringPipe
) {}
getData(){
this.boolToStringPipe.transform(true,'111','222');
}
}
4.生命周期上
angular:
ngOnChanges:当 Angular 设置或重新设置数据绑定的输入属性时响应。时间上位于OnInit之前。初始化和值发生变化时调用。
ngOnInit:用于初始化页面内容,只执行一次。时间上位于OnChanges之后。
ngDoCheck:每次变更检测时执行,并会在发生Angular自己本身不能捕获的变化时作出反应。紧跟在ngOnChanges 和 ngOnInit钩子之后执行。慎用。
ngAfterContentInit:当 Angular 把外部内容投影进组件视图或指令所在的视图之后调用。第一次 ngDoCheck 之后调用,只调用一次。
ngAfterContentChecked:每当 Angular 检查完被投影到组件或指令中的内容之后调用。ngAfterContentInit和每次 ngDoCheck之后调用。
ngAfterViewInit:当 Angular 初始化完组件视图及其子视图或包含该指令的视图之后调用。第一次 ngAfterContentChecked之后调用,只调用一次。
afterViewChecked:每当 Angular 做完组件视图和子视图或包含该指令的视图的变更检测之后调用。ngAfterViewInit和每次 ngAfterContentChecked 之后调用。
ngOnDestroy:每当 Angular 每次销毁指令/组件之前调用。
5.路由跳转
对比一下,用法差不多,router 对应 router route 对应 activeRoute
// 路由返回二者的用法
// vue
router.back();
// angular
import { Location } from '@angular/common';
constructor(private _location: Location) {}
this._location.back();
vue3:
import { useRoute, useRouter } from 'vue-router';
const route = useRoute();
const router = useRouter();
const projectId = computed(() => {
return route.params?.projectId || '';
});
const jumpUrl = async (data) => {
// 写法1 通过query传值,对应angular的queryParams
router.push({
path: `/xxxx`,
query: {
name: data.name,
},
});
// 写法2
router.push({ name: 'xxxx', params: { projectId: '1111' } });
// 写法3
router.push({ path: `/xxxx/${projectId.value}/create` });
}
};
angular:
import { ActivatedRoute, Router } from '@angular/router';
constructor(
protected router: Router,
protected activeRoute: ActivatedRoute,
) {
super(router, activeRoute);
}
ngOnInit() {
//获取路由的参数,都在activeRoute.snapshot里面,常用的是queryParams和params
this.id = this.activeRoute.snapshot.queryParams.id;
}
jumpUrl(data) {
// 写法1 最常用的,公司的项目居然找不到一个用params传值的。。。
this.router.navigate(['/xxxx'], {
queryParams: {
name: data.name,
}
});
// 写法2 params传值
// { path: 'xxxx/:id', component: Route1Component }
this.router.navigate(['/xxxx', 26]);
// url:http://localhost:4200/xxxx/26
// 获取params: const id = this.route.snapshot.params.id;
}
6.抽取hooks
区别就是angular是继承一个类,有点像Java的写法了,vue3是直接import 进来调用
vue3:
use-data-operate.ts
export useDataOperate = () => {
const name = ref();
const getData = () => {
// xxxx
}
}
index.vue:
import { useDataOperate } from './hooks/use-data-operate';
const { getData, name } = useDataOperate ();
angular:
xxx-template.ts
export class XXXTemplate{
}
index-list-component.ts:
import { xxxTemplate } from '../xxx-template';
export class indexListComponent extends xxxTemplate implements OnInit {
ngOnInit() {
}
}
7.实际开发中遇到的和vue的不同
自定义组件库不能如下写
<xxx-div />
必须这么写
<xxx-div></xxx-div>
ngif等等里面不能放函数 find findIndex等等,如下会报错,includes可以用
<div *ngIf="data.find(v=>v.id==='123')"></div>
写vue3的时候,进入界面的函数操作都是放在 onMounted 里面的,
写angular的时候,需要都放在 ngAfterViewInit() 里面才行,不能放在 ngOnInit() 里面,因为这个时候dom还没加载,读取dom的操作会报错
获取不到dom元素,不能加载echarts,有两种修改方法,第一种在ngAfterViewInit加个setTimeout 0 来模拟下vue的nexttick操作,第二种如下
<div #charts id="charts111"></div>
import { Component, OnInit, Input, SimpleChanges, ViewChild, ViewChildren, ElementRef } from '@angular/core';
@ViewChild('charts') charts: ElementRef<HTMLElement>;
// 下面这句和 const chartsDom = document.getElementById('charts111') 效果一样
const chartsDom = this.charts.nativeElement;
// 后面具体操作不写了
8.样式上
vue:
:deep(.user){
width: 100%;
}
angular:
::ng-deep .user {
width: 100%;
}
更多推荐
所有评论(0)