vue3组合式api 和 react自定义hooks
前言
其实两者是一个东西,只是叫法不通
而且显然这次是vue抄袭了react
为了对比,我举了两个例子,都用了一套数据
Mock.mock("/getStudent",options=>{
return Mock.mock({
"list|2":[{
id:()=>Random.guid(),
name: ()=>Random.cname(),
age:()=>Random.integer(1,100)
}]
})
})
vue3 组合式函数
定义组合式函数(注意:这种模式只能在vue3组合式api定义的组建下使用,即setup写法组件下使用)
// use-student.js
import axios from "axios";
import { ref } from "@vue/reactivity";
const useStudent = () => {
const student = ref([]);
const syncStudent = async () => {
const res = await axios.get("/getStudent");
student.value = res.data.list;
};
return { student, syncStudent };
};
export default useStudent;
使用
<script setup>
import useStudent from '../composables/use-student';
const { student, syncStudent } = useStudent();
</script>
<template>
<div class="home">
{{ JSON.stringify(student) }}
<button @click="syncStudent">测试</button>
</div>
</template>
reac自定义hooks
组合式函数
// use-student.js
import axios from "axios";
import { useState } from "react";
const useStudent = () => {
const [student, setStudent] = useState([]);
const syncStudent = async () => {
const res = await axios.get("/getStudent");
setStudent(res.data.list);
};
return { student, syncStudent };
};
export default useStudent;
使用
import useStudent from './hooks/use-student';
function App() {
const {student, syncStudent} = useStudent();
return (
<div className="App">
{JSON.stringify(student)}
<button onClick={syncStudent}>测试</button>
</div>
);
}
export default App;