用三种方式,写一个前端页面。页面里有一个按钮,点击后数字逐渐增加。
React
<!DOCTYPE html>
<html>
<head>
<title>React Demo</title>
</head>
<body>
<div id="root"></div>
</body>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script
async
src="https://ga.jspm.io/npm:es-module-shims@1.7.0/dist/es-module-shims.js"
></script>
<script type="importmap">
{
"imports": {
"react": "https://esm.sh/react?dev",
"react-dom/client": "https://esm.sh/react-dom/client?dev"
}
}
</script>
<script type="text/babel" data-type="module">
import React, { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { useState } from "react";
function App() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
console.log("click" + count);
}
return <button onClick={handleClick}>Clicked {count} times</button>;
}
const root = createRoot(document.getElementById("root"));
root.render(
<StrictMode>
<App />
</StrictMode>
);
</script>
</html>
核心部分
function App() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
console.log("click" + count);
}
return <button onClick={handleClick}>Clicked {count} times</button>;
}
我觉得有 3 个特点
- 异步式的,也就是 useState ,然后 count 只读,用 setCount 去写。我个人认为这样不够灵活方便。
- 数据和视图分离。
- 按钮就写在 script 里。
VUE3
<!DOCTYPE html>
<html>
<head>
<title>VUE Demo</title>
</head>
<body>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<div id="app">
<button @click="handleClick()">Clicked {{num}} times</button>
</div>
<script>
const { createApp } = Vue;
createApp({
data() {
return {
num: 0,
};
},
methods: {
handleClick() {
this.num++;
console.log("click" + this.num)
},
},
}).mount("#app");
</script>
</body>
</html>
核心部分
<div id="app">
<button @click="handleClick()">Clicked {{num}} times</button>
</div>
<script>
const { createApp } = Vue;
createApp({
data() {
return {
num: 0,
};
},
methods: {
handleClick() {
this.num++;
console.log("click" + this.num)
},
},
}).mount("#app");
</script>
特点
- num 和普通变量一样,而且可以直接用于显示。
- 按钮写在 script 外部。
- 响应式编程。
网友评论