自定义hook函数
自定义hook函数其实本质就是一个函数,把setup函数中使用的composition API进行封装
类似Vue2中的mixin
自定义hook的优势:复用代码。让setup中的逻辑更清晰易懂
用法:
写个小功能,把它封装起来。然后多处复用。
功能介绍:点击的时候,在页面上显示鼠标当前位置。
代码:
<template>
<div class="hello">
<h1>当前鼠标坐标为:X:{{point.x}} Y:{{point.y}}</h1>
</div>
</template>
<script>
import {reactive,onMounted,onBeforeUnmount} from 'vue'
export default {
name: 'Home',
setup() {
let point = reactive({
x:0,
y:0
});
function savePoint(e){
console.log(e.pageX)
console.log(e.pageY)
point.x = e.pageX;
point.y = e.pageY
}
onMounted(()=>{
window.addEventListener('click',savePoint)
});
onBeforeUnmount(()=>{
window.removeEventListener('click',savePoint)
})
return {
point
}
},
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
接下来我们把这个功能封装一下。
首先在src文件夹下面创建hooks文件夹。在hooks创建一个js文件。里面写疯转代码
usePoint.JS代码:
import {reactive,onMounted,onBeforeUnmount} from 'vue'
export default function(){
let point = reactive({
x:0,
y:0
});
function savePoint(e){
console.log(e.pageX);
console.log(e.pageY);
point.x = e.pageX;
point.y = e.pageY
}
onMounted(()=>{
window.addEventListener('click',savePoint)
});
onBeforeUnmount(()=>{
window.removeEventListener('click',savePoint)
})
return point
}
新创建一个组件,让后引用
新创Demo组件代码:
<template>
<div>
<h1>当前鼠标坐标为:X:{{point.x}} Y:{{point.y}}</h1>
</div>
</template>
<script>
//引入
import usePoint from '../hooks/usePoint'
export default {
name: "Demo",
setup(){
let point = usePoint()
return {
point
}
}
}
</script>
<style scoped>
</style>
App.vue代码:
<template>
<div id="nav">
<button @click="Show = !Show">显示/隐藏</button>
<Home v-if="Show"></Home>
<hr>
<Demo v-if="Show"></Demo>
</div>
</template>
<script>
import About from './views/About'
import Home from './views/Home'
import Demo from './views/Demo'
import {ref} from 'vue'
export default {
name: 'App',
setup() {
let Show = ref(true);
return {
Show
}
},
components: {
About,
Home,
Demo
}
}
</script>
<style lang="scss">
</style>
以上就是Vue3自定义hook用法