vue3中可以继续使用vue2中的生命周期钩子,但是有两个被更名:
beforDestroy改名为beforeUmmount
destroyed改名为unmounted
运用时需要引入,+on 示例如下:
import { onMounted,onBeforeUnmount } from "vue";
自定义hook函数:
----------本质是一个函数,把setup函数中使用的Composition API进行了封装。
类似于vue2中的mixin
自定义hook的优势:复用代码,让setup中的逻辑更清楚易懂
新建文件夹hooks ~ 新建js文件以use开头
usepoint.js中的代码:和组件使用方式:
import { reactive,onMounted,onBeforeUnmount } from "vue";
export default function (){
//实现鼠标“打点”相关的数据
let point = reactive({
x:0,
y:0
})
//“打点”相关的方法
function savePoint(event){
point.x =event.pageX
point.y = event.pageY
console.log(point.x,point.y);
}
//“打点”相关的生命周期钩子
onMounted(()=>{
window.addEventListener('click',savePoint)
})
//销毁前 清除打点
onBeforeUnmount(()=>{
window.removeEventListener('click',savePoint)
})
//不要忘了返回point
return point
}
<template>
<h2>点我获取当前坐标:x:{{point.x}},y:{{point.y}}</h2>
</template>
<script>
//引用usepoint
import usePoint from "../hooks/usepoint"
export default {
setup() {
//声明 使用接收的函数
let point = usePoint()
return {
point,
};
},
};
</script>
toRef:
作用:创建一个ref对象,其value值指向另一个对象中的某一属性。
语法:const name = toRef ( person , 'name' )
应用:要将响应式对象中的某个属性单独提供给外部使用时。
扩展:toRefs与toRef功能一致,但可以批量创建多个ref对象,语法:tpRef(person)
区别:ref是跟着复制一个,toref是引用一个,通过getter指向到值