Skip to content
大纲

React 和Vue 基础对比


显示与隐藏(条件判断)

vue3

html
<!-- 效果 -->
<div v-if="true">dom直接被销毁</div>
<div v-show="true">css的display:none隐藏了</div>

<div style="{display:true}">同v-show</div>

<div v-if="inputState===1">条件为1</div>
<div v-else="inputState===2">条件为2</div>

react18

jsx
function App() {
  const inputState = 1;
  const ShowData = () => {
    let res = null;
    if (inputState === 1) {
      res = <div>条件为1</div>;
    } else if (inputState == 2) {
      res = <div>条件为2</div>;
    }
    return res;
  };
  return (
    <div>
      {true && <div>同v-if</div>}
      <div style={{ display: "none" }}>同v-show: css的display:none隐藏了</div>
      <ShowData />
    </div>
  );
}

数据绑定

vue 双向绑定

vue
<script setup lang="ts">
import { reactive } from "vue";
const form = reactive({ userName: "", age: 0 });
const handleCnhange = (e: MouseEvent) => {
  const { value, name } = e.target;
  form[name] = value;
};
</script>
<template>
  <input type="text" v-model="form.userName" />
  <input type="number" v-model="form.age" />

  <!-- 不用语法糖,需要使用name来映射 -->
  <input
    type="text"
    name="userName"
    @input="handleCnhange"
    :value="form.userName"
  />
</template>
  • v-model 语法糖其他用法(仅限 vue3)

<childen v-model:name="name">v-model多种用法 内部使用emits("udpate:name",value)</childen>

react 实现双向绑定

jsx
import React, { useState } from "react";

function App() {
  const [form, setForm] = useState({ userName: "", age: 1 });
  const handleCnhange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { value, name } = e.target;
    setForm((preData) => {
      return { ...preData, [name]: value };
    });
  };
  return (
    <div>
      <input
        type="text"
        name="userName"
        value={form.userName}
        onChange={handleCnhange}
      />
      <input
        type="number"
        name="age"
        value={form.age}
        onChange={handleCnhange}
      />
    </div>
  );
}

缓存计算数据(优化)

vue3 computed

html
<script setup>
  import { reactive, computed } from "vue";
  const author = reactive({
    name: "breakon",
    books: ["", "", ""],
  });
  setTimeout(() => {
    author.books = [];
  }, 2000);
  // a computed ref
  const publishedBooksMessage = computed(() => {
    return author.books.length;
  });
</script>

<template>
  <p>当books属性计算属性用到的数据发生变化时才会执行该函数</p>
  <span>{{ publishedBooksMessage }}</span>
</template>
jsx
import { useState, useMemo } from 'react'
function Demo() {
  const [name, setName] = useState('666')
  const [food, setFood] = useState('大面筋')

  // 实现computed的功能
  const msg = useMemo(() => `我是${name},我爱吃${food}`, [name, food]) // 监听name和food这两个变量

  const handleClick = (type: number) => {
    if (type === 1) {
      setName('奥尔良鸡腿')
    } else if (type === 2) {
      setFood('夹肉饼')
    }
  }

  return (
    <div>
      <button onClick={() => handleClick(1)}>修改name</button>
      <button onClick={() => handleClick(2)}>修改food</button>
      <h1>{msg}</h1>
    </div>
  )
}