React、Vue3、Svelte 三大前端框架语法大比拼

2023-08-31 08:58:11 浏览数 (3)

本文将会从响应式、模板、生命周期、组件、表单、网络请求等几个方面,来对比 React、Vue3、Svelte 三大流行组件的用法区别。

响应式 - 状态

React

代码语言:javascript复制
import { useState } from "react";

export default function Name() {
  const [name] = useState("ConardLi");

  return <h1>Hello {name}</h1>;
}

Vue3

代码语言:javascript复制
<script setup>
import { ref } from "vue";
const name = ref("ConardLi");
</script>

<template>
  <h1>Hello {{ name }}</h1>
</template>

Svelte

代码语言:javascript复制
<script>
  let name = "ConardLi";
</script>

<h1>Hello {name}</h1>

响应式 - 更新状态

React

代码语言:javascript复制
import { useState } from "react";

export default function Name() {
  const [name, setName] = useState("ConardLi");
  setName("Jane");

  return <h1>Hello {name}</h1>;
}

Vue3

代码语言:javascript复制
<script setup>
import { ref } from "vue";
const name = ref("ConardLi");
name.value = "Jane";
</script>

<template>
  <h1>Hello {{ name }}</h1>
</template>

Svelte

代码语言:javascript复制
<script>
  let name = "ConardLi";
  name = "Jane";
</script>

<h1>Hello {name}</h1>

响应式 - 状态计算

React

代码语言:javascript复制
import { useState } from "react";

export default function DoubleCount() {
  const [count] = useState(10);
  const doubleCount = count * 2;

  return <div>{doubleCount}</div>;
}

Vue3

代码语言:javascript复制
<script setup>
import { ref, computed } from "vue";
const count = ref(10);
const doubleCount = computed(() => count.value * 2);
</script>

<template>
  <div>{{ doubleCount }}</div>
</template>

Svelte

代码语言:javascript复制
<script>
  let count = 10;
  $: doubleCount = count * 2;
</script>

<div>{doubleCount}</div>

模板 - 最小模板

React

代码语言:javascript复制
export default function HelloWorld() {
  return <h1>你好 code秘密花园</h1>;
}

Vue3

代码语言:javascript复制
<template>
  <h1>你好 code秘密花园</h1>
</template>

Svelte

代码语言:javascript复制
<h1>你好 code秘密花园</h1>

模板 - 样式

React

代码语言:javascript复制
import "./style.css";

export default function CssStyle() {
  return (
    <>
      <h1 className="title">I am red</h1>
      <button style={{ fontSize: "17rem" }}>I am a button</button>
    </>
  );
}

Vue3

代码语言:javascript复制
<template>
  <h1 class="title">
    I am red
  </h1>
  <button style="font-size: 17rem">
    I am a button
  </button>
</template>

<style scoped>
.title {
  color: red;
}
</style>

Svelte

代码语言:javascript复制
<h1 class="title">I am red</h1>
<button style="font-size: 17rem;">I am a button</button>

<style>
  .title {
    color: red;
  }
</style>

模板 - 循环

React

代码语言:javascript复制
export default function Colors() {
  const colors = ["red", "green", "blue"];
  return (
    <ul>
      {colors.map((color) => (
        <li key={color}>{color}</li>
      ))}
    </ul>
  );
}

Vue3

代码语言:javascript复制
<script setup>
const colors = ["red", "green", "blue"];
</script>

<template>
  <ul>
    <li
      v-for="color in colors"
      :key="color"
    >
      {{ color }}
    </li>
  </ul>
</template>

Svelte

代码语言:javascript复制
<script>
  const colors = ["red", "green", "blue"];
</script>

<ul>
  {#each colors as color}
    <li>{color}</li>
  {/each}
</ul>

模板 - 事件

React

代码语言:javascript复制
import { useState } from "react";

export default function Counter() {
  const [count, setCount] = useState(0);

  function incrementCount() {
    setCount((count) => count   17);
  }

  return (
    <>
      <p>Counter: {count}</p>
      <button onClick={incrementCount}> 17</button>
    </>
  );
}

Vue3

代码语言:javascript复制
<script setup>
import { ref } from "vue";
const count = ref(0);

function incrementCount() {
  count.value =17;
}
</script>

<template>
  <p>Counter: {{ count }}</p>
  <button @click="incrementCount">
     17
  </button>
</template>

Svelte

代码语言:javascript复制
<script>
  let count = 17;

  function incrementCount() {
    count  ;
  }
</script>

<p>Counter: {count}</p>
<button on:click={incrementCount}> 1</button>

模板 - Dom ref

React

代码语言:javascript复制
import { useEffect, useRef } from "react";

export default function InputFocused() {
  const inputElement = useRef(null);

  useEffect(() => inputElement.current.focus(), []);

  return <input type="text" ref={inputElement} />;
}

Vue3

代码语言:javascript复制
<script setup>
import { ref, onMounted } from "vue";

const inputElement = ref();

onMounted(() => {
  inputElement.value.focus();
});
</script>

<template>
  <input ref="inputElement">
</template>

Svelte

代码语言:javascript复制
<script>
  import { onMount } from "svelte";

  let inputElement;

  onMount(() => {
    inputElement.focus();
  });
</script>

<input bind:this={inputElement} />

模板 - 条件判断

React

代码语言:javascript复制
import { useState } from "react";

const TRAFFIC_LIGHTS = ["red", "orange", "green"];

export default function TrafficLight() {
  const [lightIndex, setLightIndex] = useState(0);

  const light = TRAFFIC_LIGHTS[lightIndex];

  function nextLight() {
    if (lightIndex   1 > TRAFFIC_LIGHTS.length - 1) {
      setLightIndex(0);
    } else {
      setLightIndex(lightIndex   1);
    }
  }

  return (
    <>
      <button onClick={nextLight}>Next light</button>
      <p>Light is: {light}</p>
      <p>
        You must
        {light === "red" && <span>STOP</span>}
        {light === "orange" && <span>SLOW DOWN</span>}
        {light === "green" && <span>GO</span>}
      </p>
    </>
  );
}

Vue3

代码语言:javascript复制
<script setup>
import { ref, computed } from "vue";
const TRAFFIC_LIGHTS = ["red", "orange", "green"];
const lightIndex = ref(0);

const light = computed(() => TRAFFIC_LIGHTS[lightIndex.value]);

function nextLight() {
  if (lightIndex.value   1 > TRAFFIC_LIGHTS.length - 1) {
    lightIndex.value = 0;
  } else {
    lightIndex.value  ;
  }
}
</script>

<template>
  <button @click="nextLight">
    Next light
  </button>
  <p>Light is: {{ light }}</p>
  <p>
    You must
    <span v-if="light === 'red'">STOP</span>
    <span v-else-if="light === 'orange'">SLOW DOWN</span>
    <span v-else-if="light === 'green'">GO</span>
  </p>
</template>

Svelte

代码语言:javascript复制
<script>
  const TRAFFIC_LIGHTS = ["red", "orange", "green"];
  let lightIndex = 0;

  $: light = TRAFFIC_LIGHTS[lightIndex];

  function nextLight() {
    if (lightIndex   1 > TRAFFIC_LIGHTS.length - 1) {
      lightIndex = 0;
    } else {
      lightIndex  ;
    }
  }
</script>

<button on:click={nextLight}>Next light</button>
<p>Light is: {light}</p>
<p>
  You must
  {#if light === "red"}
    <span>STOP</span>
  {:else if light === "orange"}
    <span>SLOW DOWN</span>
  {:else if light === "green"}
    <span>GO</span>
  {/if}
</p>

生命周期 - 初始化

React

代码语言:javascript复制
import { useState, useEffect } from "react";

export default function PageTitle() {
  const [pageTitle, setPageTitle] = useState("");

  useEffect(() => {
    setPageTitle(document.title);
  }, []);

  return <p>Page title: {pageTitle}</p>;
}

Vue3

代码语言:javascript复制
<script setup>
import { ref, onMounted } from "vue";
const pageTitle = ref("");
onMounted(() => {
  pageTitle.value = document.title;
});
</script>

<template>
  <p>Page title: {{ pageTitle }}</p>
</template>

Svelte

代码语言:javascript复制
<script>
  import { onMount } from "svelte";
  let pageTitle = "";
  onMount(() => {
    pageTitle = document.title;
  });
</script>

<p>Page title is: {pageTitle}</p>

生命周期 - 卸载

React

代码语言:javascript复制
import { useState, useEffect } from "react";

export default function Time() {
  const [time, setTime] = useState(new Date().toLocaleTimeString());

  useEffect(() => {
    const timer = setInterval(() => {
      setTime(new Date().toLocaleTimeString());
    }, 1000);

    return () => {
      clearInterval(timer);
    };
  }, []);

  return <p>Current time: {time}</p>;
}

Vue3

代码语言:javascript复制
<script setup>
import { ref, onUnmounted } from "vue";

const time = ref(new Date().toLocaleTimeString());

const timer = setInterval(() => {
  time.value = new Date().toLocaleTimeString();
}, 1000);

onUnmounted(() => {
  clearInterval(timer);
});
</script>

<template>
  <p>Current time: {{ time }}</p>
</template>

Svelte

代码语言:javascript复制
<script>
  import { onDestroy } from "svelte";

  let time = new Date().toLocaleTimeString();

  const timer = setInterval(() => {
    time = new Date().toLocaleTimeString();
  }, 1000);

  onDestroy(() => clearInterval(timer));
</script>

<p>Current time: {time}</p>

组件 - Props

React

App.jsx

代码语言:javascript复制
import UserProfile from "./UserProfile.jsx";

export default function App() {
  return (
    <UserProfile
      name="ConardLi"
      age={17}
      favouriteColors={["green", "blue", "red"]}
      isAvailable
    />
  );
}

UserProfile.jsx

代码语言:javascript复制
import PropTypes from "prop-types";

export default function UserProfile({
  name = "",
  age = null,
  favouriteColors = [],
  isAvailable = false,
}) {
  return (
    <>
      <p>My name is {name}!</p>
      <p>My age is {age}!</p>
      <p>My favourite colors are {favouriteColors.join(", ")}!</p>
      <p>I am {isAvailable ? "available" : "not available"}</p>
    </>
  );
}

UserProfile.propTypes = {
  name: PropTypes.string.isRequired,
  age: PropTypes.number.isRequired,
  favouriteColors: PropTypes.arrayOf(PropTypes.string).isRequired,
  isAvailable: PropTypes.bool.isRequired,
};

Vue3

App.vue

代码语言:javascript复制
<script setup>
import UserProfile from "./UserProfile.vue";
</script>

<template>
  <UserProfile
    name="ConardLi"
    :age="17"
    :favourite-colors="['green', 'blue', 'red']"
    is-available
  />
</template>

UserProfile.vue

代码语言:javascript复制
<script setup>
const props = defineProps({
  name: {
    type: String,
    required: true,
    default: "",
  },
  age: {
    type: Number,
    required: true,
    default: null,
  },
  favouriteColors: {
    type: Array,
    required: true,
    default: () => [],
  },
  isAvailable: {
    type: Boolean,
    required: true,
    default: false,
  },
});
</script>

<template>
  <p>My name is {{ props.name }}!</p>
  <p>My age is {{ props.age }}!</p>
  <p>My favourite colors are {{ props.favouriteColors.join(", ") }}!</p>
  <p>I am {{ props.isAvailable ? "available" : "not available" }}</p>
</template>

Svelte

App.svelte

代码语言:javascript复制
<script>
  import UserProfile from "./UserProfile.svelte";
</script>

<UserProfile
  name="ConardLi"
  age={17}
  favouriteColors={["green", "blue", "red"]}
  isAvailable
/>

UserProfile.svelte

代码语言:javascript复制
<script>
  export let name = "";
  export let age = null;
  export let favouriteColors = [];
  export let isAvailable = false;
</script>

<p>My name is {name}!</p>
<p>My age is {age}!</p>
<p>My favourite colors are {favouriteColors.join(", ")}!</p>
<p>I am {isAvailable ? "available" : "not available"}</p>

表单 - 文本框

React

代码语言:javascript复制
import { useState } from "react";

export default function InputHello() {
  const [text, setText] = useState("你好 code秘密花园");

  function handleChange(event) {
    setText(event.target.value);
  }

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

Vue3

代码语言:javascript复制
<script setup>
import { ref } from "vue";
const text = ref("Hello World");
</script>

<template>
  <p>{{ text }}</p>
  <input v-model="text">
</template>

Svelte

代码语言:javascript复制
<script>
  let text = "Hello World";
</script>

<p>{text}</p>
<input bind:value={text} />

表单 - 复选框

React

代码语言:javascript复制
import { useState } from "react";

export default function IsAvailable() {
  const [isAvailable, setIsAvailable] = useState(false);

  function handleChange() {
    setIsAvailable(!isAvailable);
  }

  return (
    <>
      <input
        id="is-available"
        type="checkbox"
        checked={isAvailable}
        onChange={handleChange}
      />
      <label htmlFor="is-available">Is available</label>
    </>
  );
}

Vue3

代码语言:javascript复制
<script setup>
import { ref } from "vue";

const isAvailable = ref(true);
</script>

<template>
  <input
    id="is-available"
    v-model="isAvailable"
    type="checkbox"
  >
  <label for="is-available">Is available</label>
</template>

Svelte

代码语言:javascript复制
<script>
  let isAvailable = false;
</script>

<input id="is-available" type="checkbox" bind:checked={isAvailable} />
<label for="is-available">Is available</label>

表单 - Radio

React

代码语言:javascript复制
import { useState } from "react";

export default function PickPill() {
  const [picked, setPicked] = useState("red");

  function handleChange(event) {
    setPicked(event.target.value);
  }

  return (
    <>
      <div>Picked: {picked}</div>

      <input
        id="blue-pill"
        checked={picked === "blue"}
        type="radio"
        value="blue"
        onChange={handleChange}
      />
      <label htmlFor="blue-pill">Blue pill</label>

      <input
        id="red-pill"
        checked={picked === "red"}
        type="radio"
        value="red"
        onChange={handleChange}
      />
      <label htmlFor="red-pill">Red pill</label>
    </>
  );
}

Vue3

代码语言:javascript复制
<script setup>
import { ref } from "vue";

const picked = ref("red");
</script>

<template>
  <div>Picked: {{ picked }}</div>

  <input
    id="blue-pill"
    v-model="picked"
    type="radio"
    value="blue"
  >
  <label for="blue-pill">Blue pill</label>

  <input
    id="red-pill"
    v-model="picked"
    type="radio"
    value="red"
  >
  <label for="red-pill">Red pill</label>
</template>

Svelte

代码语言:javascript复制
<script>
  let picked = "red";
</script>

<div>Picked: {picked}</div>

<input id="blue-pill" bind:group={picked} type="radio" value="blue" />
<label for="blue-pill">Blue pill</label>

<input id="red-pill" bind:group={picked} type="radio" value="red" />
<label for="red-pill">Red pill</label>

表单 - Select

React

代码语言:javascript复制
import { useState } from "react";

const colors = [
  { id: 1, text: "red" },
  { id: 2, text: "blue" },
  { id: 3, text: "green" },
  { id: 4, text: "gray", isDisabled: true },
];

export default function ColorSelect() {
  const [selectedColorId, setSelectedColorId] = useState(2);

  function handleChange(event) {
    setSelectedColorId(event.target.value);
  }

  return (
    <select value={selectedColorId} onChange={handleChange}>
      {colors.map((color) => (
        <option key={color.id} value={color.id} disabled={color.isDisabled}>
          {color.text}
        </option>
      ))}
    </select>
  );
}

Vue3

代码语言:javascript复制
<script setup>
import { ref } from "vue";

const selectedColorId = ref(2);

const colors = [
  { id: 1, text: "red" },
  { id: 2, text: "blue" },
  { id: 3, text: "green" },
  { id: 4, text: "gray", isDisabled: true },
];
</script>

<template>
  <select v-model="selectedColorId">
    <option
      v-for="color in colors"
      :key="color.id"
      :value="color.id"
      :disabled="color.isDisabled"
    >
      {{ color.text }}
    </option>
  </select>
</template>

Svelte

代码语言:javascript复制
<script>
  let selectedColorId = 2;

  const colors = [
    { id: 1, text: "red" },
    { id: 2, text: "blue" },
    { id: 3, text: "green" },
    { id: 4, text: "gray", isDisabled: true },
  ];
</script>

<select bind:value={selectedColorId}>
  {#each colors as color}
    <option value={color.id} disabled={color.isDisabled}>
      {color.text}
    </option>
  {/each}
</select>

Web 应用 - 渲染

React

index.html

代码语言:javascript复制
<!DOCTYPE html>
<html>
  <body>
    <div id="app"></div>
    <script type="module" src="./main.jsx"></script>
  </body>
</html>

App.jsx

代码语言:javascript复制
export default function App() {
  return <h1>你好 code秘密花园</h1>;
}

Main.jsx

代码语言:javascript复制
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";

ReactDOM.createRoot(document.getElementById("app")).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

Vue3

index.html

代码语言:javascript复制
<!DOCTYPE html>
<html>
  <body>
    <div id="app"></div>
    <script type="module" src="./main.js"></script>
  </body>
</html>

App.vue

代码语言:javascript复制
<!DOCTYPE html>
<html>
  <body>
    <div id="app"></div>
    <script type="module" src="./main.js"></script>
  </body>
</html>

main.js

代码语言:javascript复制
import { createApp } from 'vue'
import App from './App.vue'

createApp(App).mount('#app')

Svelte

index.html

代码语言:javascript复制
<!DOCTYPE html>
<html>
  <body>
    <div id="app"></div>
    <script type="module" src="./app.js"></script>
  </body>
</html>

App.js

代码语言:javascript复制
import App from "./App.svelte";

const app = new App({
  target: document.getElementById("app"),
});

export default app;

App.svelte

代码语言:javascript复制
<h1>你好 code秘密花园</h1>

Web 应用 - 获取数据

React

App.jsx

代码语言:javascript复制
import useFetchUsers from "./useFetchUsers";

export default function App() {
  const { isLoading, error, data: users } = useFetchUsers();

  return (
    <>
      {isLoading ? (
        <p>Fetching users...</p>
      ) : error ? (
        <p>An error occured while fetching users</p>
      ) : (
        users && (
          <ul>
            {users.map((user) => (
              <li key={user.login.uuid}>
                <img src={user.picture.thumbnail} alt="user" />
                <p>
                  {user.name.first} {user.name.last}
                </p>
              </li>
            ))}
          </ul>
        )
      )}
    </>
  );
}

useFetchUsers.js

代码语言:javascript复制
import { useEffect, useState } from "react";

export default function useFetchUsers() {
  const [data, setData] = useState();
  const [error, setError] = useState();
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    async function fetchData() {
      setIsLoading(true);
      try {
        const response = await fetch("https://conardli.top/api/?results=3");
        const { results: users } = await response.json();
        setData(users);
        setError();
      } catch (err) {
        setData();
        setError(err);
      }
      setIsLoading(false);
    }
    fetchData();
  }, []);

  return { isLoading, error, data };
}

Vue3

App.vue

代码语言:javascript复制
<script setup>
import useFetchUsers from "./useFetchUsers";

const { isLoading, error, data: users } = useFetchUsers();
</script>

<template>
  <p v-if="isLoading">
    Fetching users...
  </p>
  <p v-else-if="error">
    An error ocurred while fetching users
  </p>
  <ul v-else-if="users">
    <li
      v-for="user in users"
      :key="user.login.uuid"
    >
      <img
        :src="user.picture.thumbnail"
        alt="user"
      >
      <p>
        {{ user.name.first }}
        {{ user.name.last }}
      </p>
    </li>
  </ul>
</template>

useFetchUsers.js

代码语言:javascript复制
import { ref } from "vue";

export default function useFetchUsers() {
  const data = ref();
  const error = ref();
  const isLoading = ref(false);

  async function fetchData() {
    isLoading.value = true;
    try {
      const response = await fetch("https://conardli.top/api/?results=3");
      const { results: users } = await response.json();
      data.value = users;
      error.value = undefined;
    } catch (err) {
      data.value = undefined;
      error.value = err;
    }
    isLoading.value = false;
  }
  fetchData();

  return { isLoading, error, data };
}

Svelte

App.svelte

代码语言:javascript复制
<script>
  import useFetchUsers from "./useFetchUsers";

  const { isLoading, error, data: users } = useFetchUsers();
</script>

{#if $isLoading}
  <p>Fetching users...</p>
{:else if $error}
  <p>An error occured while fetching users</p>
{:else if $users}
  <ul>
    {#each $users as user}
      <li>
        <img src={user.picture.thumbnail} alt="user" />
        <p>
          {user.name.first}
          {user.name.last}
        </p>
      </li>
    {/each}
  </ul>
{/if}

useFetchUsers.js

代码语言:javascript复制
import { writable } from "svelte/store";

export default function useFetchUsers() {
  const data = writable();
  const error = writable();
  const isLoading = writable(false);

  async function fetchData() {
    isLoading.set(true);
    try {
      const response = await fetch("https://conardli.top/api/?results=3");
      const { results: users } = await response.json();
      data.set(users);
      error.set();
    } catch (err) {
      data.set();
      error.set(err);
    }
    isLoading.set(false);
  }
  fetchData();

  return { isLoading, error, data };
}

Web 应用 - 路由链接

React

代码语言:javascript复制
import Link from "next/link";

export default function Home() {
  return (
    <ul>
      <li>
        <Link href="/">Home</Link>
      </li>
      <li>
        <Link href="/about">About us</Link>
      </li>
    </ul>
  );
}

Vue3

代码语言:javascript复制
<template>
  <ul>
    <li>
      <NuxtLink to="/"> Home </NuxtLink>
    </li>
    <li>
      <NuxtLink to="/about"> About us </NuxtLink>
    </li>
  </ul>
</template>

Svelte

代码语言:javascript复制
<ul>
  <li>
    <a href="/">Home</a>
  </li>
  <li>
    <a href="/about">About us</a>
  </li>
</ul>

Web 应用 - 路由

React

NextJS

代码语言:javascript复制
|-- pages/
    |-- index.js // index page "/"
    |-- about.js // about page "/about"
    |-- 404.js // handle error HTTP 404 page not found
    |-- 500.js // handle error HTTP 500
    |-- _app.js // global app layout

Vue3

Nuxt 3

代码语言:javascript复制
|-- pages/
    |-- index.vue // index page "/"
    |-- about.vue // about page "/about"

Svelte

SvelteKit

代码语言:javascript复制
|-- routes/
    |--  page.svelte // index page "/"
    |-- about/
        |--  page.svelte // about page "/about"
    |--  error.svelte // handle HTTP errors 404, 500,...
    |--  layout.svelte // global app layout

最后

大家觉得哪种用法最舒服?欢迎在评论区留言!

参考:https://component-party.dev/

0 人点赞