vue3和react hook对比
useCounter
1.vue3
useCounter.js
import { ref, onMounted, onBeforeUnmount } from "vue";
export default function useCounter() {
let count = ref(0);
let timer;
onMounted(() => {
timer = setInterval(() => {
count.value++;
}, 1000);
});
onBeforeUnmount(() => {
clearInterval(timer);
});
return count;
}
HookTest.vue
<template>
<div>
The count is: {{count}}
</div>
</template>
<script setup>
import useCounter from '@/hooks/useCounter'
const count = useCounter();
</script>
2.react
useCounter.js
import { useState, useEffect } from "react";
export default function useCounter() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log("useEffect callback");
const timer = setInterval(() => {
setCount((count) => count + 1);
}, 1000);
return () => {
clearInterval(timer);
};
}, []);
return [count];
}
App.js
import useCounter from "./useCounter";
function App() {
const [count] = useCounter();
return <div>The count is:{count}</div>;
}
export default App;
usePoint
1.vue3
usePoint.js
import { reactive, onMounted, onBeforeUnmount } from "vue";
export default function usePoint() {
const data = reactive({ x: 0, y: 0 });
function savePoint(e) {
data.x = e.pageX;
data.y = e.pageY;
}
onMounted(() => {
window.addEventListener("click", savePoint);
});
onBeforeUnmount(() => {
window.removeEventListener("click", savePoint);
});
return data;
}
HookTest.vue
<template>
<div>
点击坐标:({{p.x}}, {{p.y}})
</div>
</template>
<script setup>
import usePoint from '@/hooks/usePoint'
const p = usePoint();
</script>
2.react
usePoint.js
import { useState, useEffect } from "react";
export default function usePoint() {
const [point, setPoint] = useState({ x: 0, y: 0 });
function savePoint(e) {
setPoint({ x: e.pageX, y: e.pageY });
}
useEffect(() => {
window.addEventListener("click", savePoint);
return () => {
window.removeEventListener("click", savePoint);
};
}, []);
return [point];
}
App.js
import usePoint from "./usePoint";
function App() {
const [p] = usePoint();
return (
<div>
点击坐标:({p.x}, {p.y})
</div>
);
}
export default App;