【JavaScript框架】Vue与React中的组件框架概念

news/2024/7/15 19:32:48 标签: javascript, vue.js, react.js

组件框架是用于构建应用程序的工具,以便将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中实现这些概念。鉴于这些概念通常在组件框架中使用,一旦熟悉了这些概念的工作原理,就可以相对容易地从一个框架过渡到另一个框架。


http://www.niftyadmin.cn/n/5222605.html

相关文章

hive两张表实现like模糊匹配关联

testa表(字段a)aaabbacccddddddaaatestb表(字段b)ab1. 使用likeconcat模糊配对 selecta.a from testa a ,testb b where a like concat(%,b.b,%) group by a.a2. 使用locate函数 selecta.a from testa a ,testb b where locate(b.b,a.a)>0 group by a.a3. 使用instr函数 sel…

json处理由fastjson换jackjson

fastjson没有jackjson稳定&#xff0c;所以换成jackjson来处理对象转json和json转对象问题。 首先下载jackjson包&#xff0c;三个都要引用 然后修改实现类 package JRT.Core.Util;import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.ja…

删除链表的倒数第N个节点,剑指offerII(21),力扣

目录 题目地址&#xff1a; 题目&#xff1a; 相似类型题&#xff1a; 我们直接看本题题解吧&#xff1a; 解题方法&#xff1a; 难度分析&#xff1a; 解题分析&#xff1a; 解题思路&#xff08;双指针&#xff09;&#xff1a; 代码实现&#xff1a; 代码说明&#xff1a; 代…

vue3中的customRef创建一个自定义的 ref对象

customRef 创建一个自定义的 ref&#xff0c;并对其依赖项跟踪和更新触发进行显式控制 小案例: 自定义 ref 实现 debounce <template><div style"font-size: 14px;"><input v-model"text" placeholder"搜索关键字"/><…

第八节HarmonyOS @Component自定义组件的生命周期

在开始之前&#xff0c;我们先明确自定义组件和页面的关系&#xff1a; 1、自定义组件&#xff1a;Component装饰的UI单元&#xff0c;可以组合多个系统组件实现UI的复用。 2、页面&#xff1a;即应用的UI页面。可以由一个或者多个自定义组件组成&#xff0c;Entry装饰的自定…

MySQL数据库【一】

博学而笃志&#xff0c;切问而近思 文章目录 数据库简介服务器、数据库以及表的关系连接数据库数据库操作命令创建数据库查看数据库创建语句查看数据库使用数据库修改数据库删除数据库 数据库字符集和校验规则查看系统默认字符集查看系统默认校验规则查看数据库支持的字符集查看…

C++——vector互换容器与预留空间

一.vector互换容器 功能描述:实现两个容器内元进行互换 函数原型: swap(vec); //将vec与本身的元素互换 实例: //1.基本使用 void test01() {vector<int>v1;for (int i 0; i < 10; i){v1.push_back(i);}cout << "交换前:" << e…

springcloud进销存管理系统源码

开发说明&#xff1a; jdk1.8&#xff0c;mysql5.7&#xff0c;idea&#xff0c;vscode springcloud springboot mybatis vue elementui 功能介绍&#xff1a; 后台管理&#xff1a; 统计分析&#xff1a;查看产品&#xff0c;采购&#xff0c;销售数量&#xff1b;统计近…