vue3和react使用hook示例对比useCounter、usePoint

2 篇文章 0 订阅

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;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值