发布于 2026-01-06 0 阅读
0

JavaScript Unlocked: Effortlessly Master React, Vue, and Angular

JavaScript Unlocked: Effortlessly Master React, Vue, and Angular

介绍

如果你精通 JavaScript,你会发现学习 React、Vue 和 Angular 等前端框架会变得容易得多。这些框架有很多共同的底层原理和模式,这意味着一旦你熟练掌握其中一个,学习其他框架就会容易得多。理解 JavaScript 的基础知识,例如状态管理、组件化架构、事件处理和双向数据绑定,将为你驾驭和精通这些框架打下坚实的基础。

在本指南中,我们将比较 React、Vue 和 Angular,重点关注它们如何处理状态管理、组件生命周期、refs、props、双向数据绑定以及子组件向父组件发送事件等常见任务。通过理解每个框架的核心概念,您将发现它们之间的相似之处,以及如何将您的 JavaScript 技能无缝地迁移到其他框架中。

状态管理:

React

在 React 中,组件内部的状态管理是通过 hooks 来处理的,例如useState

import React, { useState } from 'react';

function MyComponent() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

在Angular中,状态通常使用服务进行管理,而BehaviorSubject对于更复杂的状态管理,则使用RxJS:

// counter.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class CounterService {
  private countSubject = new BehaviorSubject<number>(0);
  count$ = this.countSubject.asObservable();

  increment() {
    this.countSubject.next(this.countSubject.value + 1);
  }
}

// my-component.component.ts
import { Component } from '@angular/core';
import { CounterService } from './counter.service';

@Component({
  selector: 'app-my-component',
  template: `
    <div>
      <p>Count: {{ count | async }}</p>
      <button (click)="increment()">Increment</button>
    </div>
  `,
})
export class MyComponent {
  count = this.counterService.count$;

  constructor(private counterService: CounterService) {}

  increment() {
    this.counterService.increment();
  }
}
Enter fullscreen mode Exit fullscreen mode

维尤

在 Vue 中,可以使用data本地状态选项来管理状态,而 Vuex 则用于更复杂的状态管理:

// MyComponent.vue
<template>
  <div>
    <p>Count: {{ count }}</p>
    <button @click="increment">Increment</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      count: 0,
    };
  },
  methods: {
    increment() {
      this.count += 1;
    },
  },
};
</script>
Enter fullscreen mode Exit fullscreen mode

组件生命周期:

React

React 使用生命周期方法来useEffect处理副作用:

import React, { useEffect } from 'react';

function MyComponent() {
  useEffect(() => {
    console.log('Component mounted');
    return () => {
      console.log('Component unmounted');
    };
  }, []);

  return <div>My Component</div>;
}
Enter fullscreen mode Exit fullscreen mode

Angular 生命周期钩子是诸如 `get_close()` 和 `get_close()` 之类的ngOnInit方法ngOnDestroy

import { Component, OnInit, OnDestroy } from '@angular/core';

@Component({
  selector: 'app-my-component',
  template: '<div>My Component</div>',
})
export class MyComponent implements OnInit, OnDestroy {
  ngOnInit() {
    console.log('Component mounted');
  }

  ngOnDestroy() {
    console.log('Component unmounted');
  }
}
Enter fullscreen mode Exit fullscreen mode

维尤

Vue 生命周期钩子包括诸如 `get_add()` 和 `get_add_require()` 之类的mounted方法beforeDestroy

export default {
  template: '<div>My Component</div>',
  mounted() {
    console.log('Component mounted');
  },
  beforeDestroy() {
    console.log('Component unmounted');
  },
};
Enter fullscreen mode Exit fullscreen mode

参考文献:

React

React 用于useRef引用 DOM 元素:

import React, { useRef } from 'react';

function MyComponent() {
  const inputRef = useRef(null);

  const focusInput = () => {
    inputRef.current.focus();
  };

  return (
    <div>
      <input ref={inputRef} />
      <button onClick={focusInput}>Focus Input</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

在 Angular 中,ViewChild用于引用 DOM 元素:

import { Component, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'app-my-component',
  template: `
    <input #inputElement />
    <button (click)="focusInput()">Focus Input</button>
  `,
})
export class MyComponent {
  @ViewChild('inputElement') inputElement: ElementRef;

  focusInput() {
    this.inputElement.nativeElement.focus();
  }
}
Enter fullscreen mode Exit fullscreen mode

维尤

Vue 使用该ref属性来引用 DOM 元素:

<template>
  <div>
    <input ref="inputElement" />
    <button @click="focusInput">Focus Input</button>
  </div>
</template>

<script>
export default {
  methods: {
    focusInput() {
      this.$refs.inputElement.focus();
    },
  },
};
</script>
Enter fullscreen mode Exit fullscreen mode

组件属性:

React

在 React 中,props 通过属性传递给组件:

function MyComponent({ message }) {
  return <div>{message}</div>;
}

// Usage
<MyComponent message="Hello, World!" />
Enter fullscreen mode Exit fullscreen mode

在 Angular 中,@Input用于将数据传递给子组件:

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-my-component',
  template: '<div>{{ message }}</div>',
})
export class MyComponent {
  @Input() message: string;
}

// Usage in a parent component template
<app-my-component [message]="'Hello, World!'"></app-my-component>
Enter fullscreen mode Exit fullscreen mode

维尤

在 Vue 中,props 通过模板中的属性传递:

<template>
  <div>{{ message }}</div>
</template>

<script>
export default {
  props: ['message'],
};
</script>

<!-- Usage -->
<MyComponent message="Hello, World!" />
Enter fullscreen mode Exit fullscreen mode

双向装订:

React

React 没有内置的双向数据绑定。状态是通过回调函数更新的:

function MyComponent() {
  const [value, setValue] = useState('');

  return (
    <input
      value={value}
      onChange={(e) => setValue(e.target.value)}
    />
  );
}
Enter fullscreen mode Exit fullscreen mode

Angular 提供双向绑定ngModel

import { Component } from '@angular/core';

@Component({
  selector: 'app-my-component',
  template: '<input [(ngModel)]="value" />',
})
export class MyComponent {
  value: string = '';
}
Enter fullscreen mode Exit fullscreen mode

维尤

Vue 提供双向绑定,可通过v-model指令实现:

<template>
  <input v-model="value" />
</template>

<script>
export default {
  data() {
    return {
      value: '',
    };
  },
};
</script>
Enter fullscreen mode Exit fullscreen mode

亲子沟通(事件发射):

维尤

在 Vue 中,子组件可以发出事件,父组件可以监听该事件并做出相应的响应。

子组件(MyChildComponent.vue):

<template>
  <button @click="notifyParent">Click me</button>
</template>

<script>
export default {
  methods: {
    notifyParent() {
      this.$emit('childClicked', 'Some data from child');
    },
  },
};
</script>
Enter fullscreen mode Exit fullscreen mode

父组件(MyParentComponent.vue):

<template>
  <div>
    <MyChildComponent @childClicked="handleChildClick" />
  </div>
</template>

<script>
import MyChildComponent from './MyChildComponent.vue';

export default {
  components: {
    MyChildComponent,
  },
  methods: {
    handleChildClick(data) {
      console.log('Event received from child:', data);
    },
  },
};
</script>
Enter fullscreen mode Exit fullscreen mode

React

在 React 中,通常的做法是将一个回调函数作为 prop 传递给子组件。子组件调用这个函数来通知父组件。

子组件(MyChildComponent.js):

function MyChildComponent({ onChildClick }) {
  return (
    <button onClick={() => onChildClick('Some data from child')}>Click me</button>
  );
}

export default MyChildComponent;
Enter fullscreen mode Exit fullscreen mode

父组件(MyParentComponent.js):

import React from 'react';
import MyChildComponent from './MyChildComponent';

function MyParentComponent() {
  const handleChildClick = (data) => {
    console.log('Event received from child:', data);
  };

  return (
    <div>
      <MyChildComponent onChildClick={handleChildClick} />
    </div>
  );
}

export default MyParentComponent;
Enter fullscreen mode Exit fullscreen mode

在 Angular 中,子组件使用事件监听器发出事件EventEmitter,父组件监听这些事件。

子组件(my-child.component.ts):

import { Component, Output, EventEmitter

 } from '@angular/core';

@Component({
  selector: 'app-my-child',
  template: '<button (click)="notifyParent()">Click me</button>',
})
export class MyChildComponent {
  @Output() childClicked = new EventEmitter<string>();

  notifyParent() {
    this.childClicked.emit('Some data from child');
  }
}
Enter fullscreen mode Exit fullscreen mode

父组件(my-parent.component.ts):

import { Component } from '@angular/core';

@Component({
  selector: 'app-my-parent',
  template: '<app-my-child (childClicked)="handleChildClick($event)"></app-my-child>',
})
export class MyParentComponent {
  handleChildClick(data: string) {
    console.log('Event received from child:', data);
  }
}
Enter fullscreen mode Exit fullscreen mode

概括:

  • React:使用 hooks 和 props 来管理状态和通信。它非常灵活,允许自定义解决方案。
  • Vue:通过内置指令(例如)v-model和事件发射,提供结构和灵活性的平衡$emit
  • AngularEventEmitter :提供了一个全面的框架,内置了使用服务进行状态管理、通信和双向绑定的解决方案ngModel

理解每个框架中的这些核心概念,将使您能够充分利用您的 JavaScript 技能,并在 React、Vue 和 Angular 之间轻松转换,从而使您成为一名多才多艺、高效的前端开发人员。

文章来源:https://dev.to/bilelsalemdev/javascript-unlocked-effortless-master-react-vue-and-angular-4773