自定义hook

什么是hook?

—本质上是一个函数,把setup函数中使用的Composition API进行了封装

类似于vue2中的mixin

自定义hook的优势:

复用代码,让setup中的逻辑更清楚易懂

示例

初级写法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<template>
<h2>当前求和为:{{sum}}</h2>
<button @click="sum++">点我+1</button>
<hr>
<h2>当前点击时鼠标的坐标为:x:{{point.x}},y:{{point.y}}</h2>
</template>
<script>
import {ref,reactive,onMounted,onBeforeUnmount} from 'vue'
export default {
name: "Demo",
setup(){
let sum=ref(0)

let point=reactive({
x:0,
y:0
})

function savePoint(event){
point.x=event.pageX
point.y=event.pageY
}

onMounted(()=>{
window.addEventListener('click',savePoint)
console.log('click事件挂载成功')
})

onBeforeUnmount(()=>{
window.removeEventListener('click',savePoint)
console.log('click事件即将被卸载')
})


return {
sum,point
}
},
}
</script>

<style scoped>

</style>

钩子写法(usePoint.js):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import {onBeforeUnmount, onMounted, reactive} from "vue";

export default function (){
//实现鼠标打点相关的数据
let point=reactive({
x:0,
y:0
})
//实现鼠标打点相关的方法
function savePoint(event){
point.x=event.pageX
point.y=event.pageY
}
//实现鼠标打点相关的生命周期钩子
onMounted(()=>{
window.addEventListener('click',savePoint)
console.log('click事件挂载成功')
})

onBeforeUnmount(()=>{
window.removeEventListener('click',savePoint)
console.log('click事件即将被卸载')
})

return point

}

组件中使用usePoint.js

1
2
3
4
5
6
7
8
9
setup(){
let sum=ref(0)

let point=usePoint()

return {
sum,point
}
}