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

news2024/9/24 17:18:10

组件框架是用于构建应用程序的工具,以便将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.coloradmin.cn/o/1263547.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

使用.NET8中的.http文件和终结点资源管理器

本文将以.NET8的模板增加的.http文件为引&#xff0c;介绍 Visual Studio 2022 中的 .http 文件编辑器&#xff0c;这是一个用于测试 ASP.NET Core 项目的强大工具。 文章目录 1. 背景2. HTTP 文件介绍2.1 简介2.2 .http 文件语法3. 在 Visual Studio 中使用3.1 终结点资源管理…

大数据平台/大数据技术与原理-实验报告--部署全分布模式HBase集群和实战HBase

实验名称 部署全分布模式HBase集群和实战HBase 实验性质 &#xff08;必修、选修&#xff09; 必修 实验类型&#xff08;验证、设计、创新、综合&#xff09; 综合 实验课时 2 实验日期 2023.11.07-2023.11.10 实验仪器设备以及实验软硬件要求 专业实验室&#xff…

【Apifox】测试工具自动编写接口文档

在开发过程中&#xff0c;我们总是避免不了进行接口的测试&#xff0c; 而相比手动敲测试代码&#xff0c;使用测试工具进行测试更为便捷&#xff0c;高效 今天发现了一个非常好用的接口测试工具Apifox 相比于Postman&#xff0c;他还拥有一个非常nb的功能&#xff0c; 在接…

交流负载测试使用场景

交流负载测试是一种在特定环境下&#xff0c;对电力设备、汽车电子部件&#xff0c;工业自动化设备、网络设备、家电产品&#xff0c;航空航天设备以及医疗器械等产品进行测试的方法&#xff0c;该测试的目的是评估这些设备在实际运行条件下的性能和可靠性。 1电力设备测试 交…

没有预装Edge浏览器的Windows系统安装Edge正式版的方法,离线安装和在线安装

一、在线安装 没有预装Edge浏览器的Windows系统安装Edge正式版的方法 二、离线安装 进入到下面这个目录 C:\Program Files (x86)

vivado产生报告阅读分析27

1、设计 QoR 汇总 命令行选项 -qor_summary 可用于为流程中每个步骤生成 QoR 汇总信息。该选项只能从 Tcl 控制台使用。该选项可按两种格式生成&#xff1a; 基于文本的报告或 JSON 格式。 要生成基于文本的格式 &#xff0c; 请运行以下命令 &#xff1a; report_des…

Jquery动画特效

1&#xff0c;Jquery提供的特效方法 2&#xff0c;实例代码 <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><…

冒泡排序以及改进方案

冒泡排序以及改进方案 介绍&#xff1a; 冒泡排序属于一种典型的交换排序&#xff08;两两比较&#xff09;。冒泡排序就像是把一杯子里的气泡一个个往上冒一样。它不断比较相邻的元素&#xff0c;如果顺序不对就像水泡一样交换它们的位置&#xff0c;直到整个序列像水泡一样…

矩阵连乘问题

1、求解矩阵连乘问题。 要求: 分别用自底向上的动态规划方法和自顶向下的备忘录方法计算最优值并构造最优解&#xff0c;通过实例比较两种方法的结果和效率。 思路 1)寻找最优子结构&#xff1a; 此问题最难就在于此&#xff0c;对于乘积的任意位置加括号都会将序列在某个…

C#简化工作之实现网页爬虫获取数据

1、需求 想要获取网站上所有的气象信息&#xff0c;网站如下所示&#xff1a; 目前总共有67页&#xff0c;随便点开一个如下所示&#xff1a; 需要获取所有天气数据&#xff0c;如果靠一个个点开再一个个复制粘贴那么也不知道什么时候才能完成&#xff0c;这个时候就可以使用C#…

unity3d NPC寻路时相互挤压、导致离目标越来越远

更改寻路代理 约束的大小&#xff0c;人物周围绿色圆柱范围线&#xff0c;尽量调小

23种设计模式之C++实践

23种设计模式之C++实践 1. 简介2. 基础知识3. 设计模式(一)创建型模式1. 单例模式1.2 饿汉式单例模式1.3 懒汉式单例模式比较IoDH单例模式总结2. 简单工厂模式简单工厂模式总结3. 工厂方法模式工厂方法模式总结4. 抽象工厂模式抽象工厂模式总结5. 原型模式原型模式总结6. 建造…

MySQL索引优化实战一

#插入一些示例数据drop procedure if exists insert_emp;delimiter ;;create procedure insert_emp()begindeclare i int;set i1;while(i<100000)doinsert into employees(name,age,position) values(CONCAT(tqq,i),i,dev);set ii1;end while;end;;delimiter ;call insert_e…

linaro交叉编译工具链下载与使用笔记

笔记 文章目录 笔记确定目标 &#xff08;aarch64&#xff09;选择版本&#xff08;7.5&#xff09;选择目标&#xff08;aarch64-linux-gnu&#xff09;下载地址工具链&#xff08;gcc-linaro-7.5.0-2019.12-x86_64_aarch64-linux-gnu.tar.xz&#xff09;编译测试 &#xff08…

WIFI模块(esp-01s)实现天气预报代码实现

目录 前言 实现图片 一、串口编程的实现 二、发送AT指令 esp01s.c esp01s.h 三、数据处理 1、初始化 2、cjson处理函数 3、核心控制代码 四、修改堆栈大小 前言 实现图片 前面讲解了使用AT指令获取天气与cjson的解析数据&#xff0c;本章综合将时间显示到屏幕 一、…

Python超级详细的变量命名规则

Python 需要使用标识符给变量命名&#xff0c;其实标识符就是用于给程序中变量、类、方法命名的符号&#xff08;简单来说&#xff0c;标识符就是合法的名字&#xff09;。 Python 语言的标识符必须以字母、下画线&#xff08;_&#xff09;开头&#xff0c;后面可以跟任意数目…

Python单元测试之道:从入门到精通的全面指南

在这篇文章中&#xff0c;我们会深入探讨Python单元测试的各个方面&#xff0c;包括它的基本概念、基础知识、实践方法、高级话题&#xff0c;如何在实际项目中进行单元测试&#xff0c;单元测试的最佳实践&#xff0c;以及一些有用的工具和资源 一、单元测试重要性 测试是软…

ELk部署,保姆级教学超详细!!!

Elk&#xff08;Elasticsearch, Logstash, Kibana&#xff09;是一套日志收集、存储和展示方案&#xff0c;是由Elastic公司开发的开源软件组合。 Elasticsearch&#xff1a;是一个分布式的搜索和分析引擎。它能够处理大量的数据&#xff0c;并提供快速、准确的搜索结果&#x…

在线 SQL 模拟器SQL Fiddle使用简介

在线 SQL 模拟器SQL Fiddle使用简介 有时候&#xff0c;我们想去验证 SQL语句&#xff0c;却缺少数据库环境&#xff0c;那该怎么办呢&#xff1f; 这时候在线 SQL 模拟器就有了用武之地。SQL 模拟器免安装&#xff0c;可以在网页直接运行 SQL 。 SQL Fiddle 支持 MySQL、Orac…

Stable Diffusion绘画系列【4】:可爱盲盒风人物

《博主简介》 小伙伴们好&#xff0c;我是阿旭。专注于人工智能、AIGC、python、计算机视觉相关分享研究。 ✌更多学习资源&#xff0c;可关注公-仲-hao:【阿旭算法与机器学习】&#xff0c;共同学习交流~ &#x1f44d;感谢小伙伴们点赞、关注&#xff01; 《------往期经典推…