定义
什么是hook?
- 本质是一个函数,把 setup 函数中使用的 Composition API (组合API)进行了封装
- 类似于 vue2.x 中的 mixin
自定义 hook 的优势:
- 复用代码,让 setup 中的逻辑更清楚易懂
使用
首先我们做一个功能,鼠标点击屏幕,获取坐标:
<template>
<h2>当前鼠标的坐标是:x:{{ point.x }},y:{{ point.y }}</h2>
</template>
<script>
import {onMounted, onBeforeUnmount,reactive} from 'vue'
export default {
name: 'Demo',
setup() {
let point = reactive({
x: 0,
y: 0
})
function savePoint(event) {
point.x = event.pageX;
point.y = event.pageY;
}
onMounted(() => {
window.addEventListener("click",savePoint)
})
onBeforeUnmount(()=>{
window.removeEventListener("click",savePoint)
})
return {
point,
}
},
}
</script>
然后改用使用 hooks,在 src 下新建 hooks 文件夹,增加 usePoint.js
import {onBeforeUnmount, onMounted, reactive} from "vue/dist/vue";
function savePoint() {
let point = reactive({
x: 0,
y: 0
})
function savePoint(event) {
point.x = event.pageX;
point.y = event.pageY;
}
onMounted(() => {
window.addEventListener("click",savePoint)
})
onBeforeUnmount(()=>{
window.removeEventListener("click",savePoint)
})
return point
}
export default savePoint;
或者简写:
......
export default function() {
......
}
在 Demo.vue 中使用:
<template>
<h2>当前鼠标的坐标是:x:{{ point.x }},y:{{ point.y }}</h2>
</template>
<script>
import usePoint from "@/hooks/usePoint";
export default {
name: 'Demo',
setup() {
let point = usePoint()
return {
point
}
},
}
</script>
封装发ajax请求的hook函数(ts版本)
hooks 下新建 useRequest.ts
由于用到了 axios,所以安装axios:npm install axios
import {ref} from "vue";
import axios from "axios";
export default function <T>(url: string) {
const loading = ref(true);
const data = ref<T | null>(null);
const errorMsg = ref('');
axios.get(url).then(response => {
loading.value = false
data.value = response.data
}).catch(error => {
loading.value = false
errorMsg.value = error.message || '未知错误'
})
return {
loading,
data,
errorMsg
}
}
App.vue:
<template>
<h3 v-if="loading">加载中...</h3>
<h3 v-else-if="errorMsg">错误信息:{{errorMsg}}</h3>
<!-- 对象 -->
<ul v-else>
<li>{{data.name}}</li>
<li>{{data.address}}</li>
<li>{{data.distance}}</li>
</ul>
<!-- 数组 -->
<ul v-for="item in data" :key="item.name">
<li>{{item.name}}</li>
<li>{{item.address}}</li>
<li>{{item.distance}}</li>
</ul>
</template>
<script lang="ts">
import {defineComponent, watch} from 'vue';
import useRequest from "@/hooks/useRequest";
export default defineComponent({
setup() {
// 定义接口
interface IAddress{
name:string,
address:string,
distance:string
}
//const {loading,data,errorMsg} = useRequest<IAddress>("./address.json")//获取对象数据
const {loading,data,errorMsg} = useRequest<IAddress[]>("./addressList.json")//获取对象数据
watch(data, () => {
if (data.value) {
console.log(data.value.length)
}
})
return {
loading,
data,
errorMsg
}
}
});
</script>
测试数据有对象类型的 address.json:
{
"name": "家",
"address": "开发区人民路22号",
"distance": "100km"
}
还有数组类型的 addressList.json
到此这篇关于详解Vue 自定义hook 函数的文章就介绍到这了,更多相关Vue 自定义hook 内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!