跳转到主要内容

组件框架是用于构建应用程序的工具,以便将UI和逻辑划分为单独的可重用组件。目前的组件框架包括React、Vue、Angular、Ember、Svelte等。

Vue和React使用了常见的框架概念,如处理状态、道具、引用、生命周期挂钩、事件等。这两个框架在当今的web开发中被广泛使用。它们使用几乎相似的模式以可重用组件的形式构建UI,但在这篇博客文章中,您将了解组件框架的概念,以及与在React中的实现方式相比,它们在Vue中是如何实现的。

安装和设置

让我们从比较两个框架的安装过程开始。

Vue

To install Vue CLI (command line interface), the following command is used:

npm install -g @vue/cli

To check the version, run the following command in your terminal.

vue --version

To create a new project, run the following command.

vue create project_name
cd project_name
npm run serve

React

To install React, run the following command on your terminal:

npm install -g create-react-app

To create a new project, run the following command.

npx create-react-app project_name
cd project_name
npm run start

Props

组件框架使用props将数据从父组件传递到子组件,这是两者的关键技术。

Vue

在Vue中,使用引号或使用v-bind指令的变量将props作为字符串传递,该指令也可以写成:字符。

Passing props to child component

// passing props from to Modal component
<template>
  <Modal :isOpen="pageLoaded" title="Survey Form" />
</template>

Accessing props in child component

// Modal Component
<template>
  <form v-if="isOpen">
    <p>{{ title }} </p>
    <!-- ...other form elements -->
  </form>
</template>

<script setup>
  const props = defineProps({
    isOpen: Boolean,
    title: String
  });
</script>

React

在React中,props以字符串的形式传递,也使用引号或使用大括号的变量,如下所示:

Passing props

<div>
  <Modal isOpen={pageLoaded} title="Survey Form" />
</div>

Accessing props

function Modal({isOpen, title}) {
  return (
    {isOpen &&
     <form>
        <p>{ title }</p>
        // ...other form elements
      </form>
  );
}

Events

组件可以监听特定的事件,例如鼠标事件(例如,点击、鼠标悬停等)和键盘事件(例如按键向下、按键向上等)。在这两个框架中,事件处理也是必要的。

Vue

In Vue, events are created using the v-on directive, which can also be written as @ like so

<template>
    <button @click="displayName"> Show Name </button>
<template>

<script setup>
    function displayName() {
        alert('Lawrence Franklin');
    }
</script>

React

In React, events are created using the typical JavaScript inline event methods such as onClick, onKeyDown, onKeyUp, etc.

function NameAlert() {
    const displayName = () => {
        alert('Lawrence Franklin');
    }

    return (
        <button onClick="displayName"> Show Name </button>
    );
}

State

组件框架使用状态来管理组件内的反应性。状态在各个组件之间实时更新。通过网站处理全球状态是一个关键问题。

Vue

In Vue, states can be created using the ref() or reactive() method, which does the same thing except ref are accessed using the .value property while reactive are used directly (they’re already unwrapped). These methods help to creative reactivity within components.

<template>
  <div>
    <p>{{ firstname }}</p>
    <p>{{ lastname }}</p>
  </div>
</template>

<script setup>
  import { ref, reactive } from 'vue';
  
  const firstname = ref('Franklin');
  console.log(firstname.value);

  const lastname = reactive('Lawrence');
  console.log(lastname);
</script>

可以使用watch()和watchEffect()方法监视反应值。这些方法跟踪反应值的变化,并在这些值每次变化时运行回调函数。这些方法之间的唯一区别是watchEffect()最初运行一次,然后开始监视更改。

import { watch, watchEffect } from 'vue';

// watch
watch( firstname, () => alert('firstname changed!');

// watchEffect
watchEffect(lastname, () => alert('lastname changed');

React

React uses the useState() hook to track state changes in a component and create side effects.

import { useState } from 'react';

function ShowName() {
  const [firstName, setFirstName] = useState('Franklin');
  const [lastName, setLastName] = useState('Lawrence');

  console.log(firstName, lastName);

  return (
    <div>
      <p>{ firstname }</p>
      <p>{ lastname }</p>
    </div>
  )
}

为了监听状态变化,React使用useEffect()钩子。这个钩子接受一个回调函数和一个依赖项数组,每当这些依赖项的值发生变化时,它就会触发回调函数。依赖项可以是任何数据类型。以下是一个示例:

import { useEffect } from 'React';

useEffect(() => {
  console.log('name updated!');
}, [firstName, lastName]);

Open Source Session Replay

OpenReplay 是一个开源的会话回放套件,可以让你看到用户在你的网络应用程序上做什么,帮助你更快地解决问题。OpenReplay是自托管的,可完全控制您的数据。

replayer.png

Start enjoying your debugging experience - start using OpenReplay for free.

Refs

有时,您需要直接使用DOM元素,例如添加一些动画、将输入字段设置为焦点或模糊等。为此,大多数组件框架都为您提供了引用功能(Vue和React使用ref),可用于引用DOM元素。

Vue

In Vue, template ref written with the ref keyword is used on the DOM element and accessed like so:

<template>
  <input type="text" ref="name" />
</template>

<script setup>
  import { ref } from 'vue';

  const name = ref(null);

  handleBtnClick(() => {
    name.value.focus();
  }
</script>

React

In React, refs are used a bit differently. They reference DOM elements using the ref keyword and the useRef() hook, which are then accessed using the .current property like so:

 import { useRef } from 'react';

function MyName() {
  const name = useRef(null);

  handleBtnClick(() => {
    name.current.focus();
  });

  return (
    <input type="text" ref="name" />
    <button onClick={handleBtnClick}> Start typing </button>
  )
}

Two-way Data Binding

数据可以(并且通常)以“双向”绑定,这意味着数据可以通过两种方式更新。这与表单输入字段一起使用,如输入元素、选择元素、文本区域元素、复选框元素等。输入值可以通过元素和代码进行更改,以使它们同步,即,以一种方式(例如,在代码中)进行更改会更新另一个实例(例如,输入字段中)中的值。

Vue

Vue uses the v-model directive to create a two-way binding like so:

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

<script setup>
import { ref } from 'vue';

const searchQuery = ref('');
// searchQuery.value can be updated here, and it reflects in the input field instantly
</script>

React

React uses something called controlled inputs to bind data two-way like so:

import { useState } from 'react';

function MyComponent() {
  [searchQuery, setSearchQuery] = useState('');

  const handleChange = (event) => {
     setSearchQuery(event.target.value);
  }

  return (
    <input value={searchQuery} onChange={handleChange}/>
  );
}

Dynamic Rendering

有时,组件会根据特定条件进行渲染。换句话说,组件可以根据指定条件的结果进行动态渲染。

Vue

Vue uses the v-ifv-else and v-show directives to render a component dynamically based on a specified condition. The example below illustrates this concept:

<template>
  <div>
    <p v-if="isLoggedIn"> Welcome </p>
    <p v-else> Please Login </p>
    <button v-show="!isLoggedIn">Login</button>
  </div>
</template>

React

React leverages JavaScript’s conditionals such as if&&, or ternary operator to dynamically render a component. Here’s an example to illustrate this:

function MyComponent() {
  return (
    {isLoggedIn ? 
     <p>Welcome</p> :
     <p> Please Login </p>
    }
    {!isLoggedIn && <button> Login </button>}
  );
}

Passing Children

有时您希望将子元素传递给其他组件,而不仅仅是道具。像Vue和React这样的组件框架为您提供了实现这一点的方法。

Vue

Vue makes use of slots to pass children elements. Here’s an example of how you can use them:

Modal Component, this is the component that receives children elements

// Modal.vue

<template>
  <div>
    <h1>Welcome</h1>
    <slot><slot>
  </div>
</template>

UserPage Component, this is the parent component that passes the children elements

// UserPage.vue

<template>
  <div>
    <h1>Survey Form</h1>
    <Modal>
        <p>Kindly fill out this survey...</p>
        <input type="text" />
        <button>Submit</button>
    </Modal>
  </div>
</template>

React

React provides you with the children prop value similar to slots from Vue to pass children elements. Here’s an example:

Modal Component, this is the component that receives children elements

function Modal( {children} ) {
  return (
    <div>
       <h1>Welcome</h1>
       { children }
    </div>
  );
}

UserPage Component, this is the parent component that passes the children elements

 function UserPage() {
  return (
     <div>
      <h1>Survey Form</h1>
      <Modal>
        <p>Kindly fill out this survey...</p>
        <input type="text" />
        <button>Submit</button>
      </Modal>
    </div>
  );
}

结论

在这一点上,您已经了解了组件框架中使用的大多数概念,如状态、道具、组件、事件等。您还了解了如何在Vue与React中实现这些概念。鉴于这些概念通常在组件框架中使用,一旦熟悉了这些概念的工作原理,就可以相对容易地从一个框架过渡到另一个框架。