vue3中自定义hook函数
1.示例:需求当用户点击的时候,收集横纵坐标,将他们展示在页面上
setup () {
const x = ref(-1);
const y = ref(-1);
const clickHandler = (event:MouseEvent) => {
x.value = event.pageX;
y.value = event.pageY;
}
onMounted(()=>{
window.addEvnetListener('click',clickHandler)
})
onBeforeUnmount(()=>{
window.removeEventListener('click',clickHandler)
})
return {
x.y
}
}
一般情况下hook函数都是use开头的,接下来将上面的修改为hook形式
export default function() {
const x = ref(-1);
const y = ref(-1);
const clickHandler = (event:MouseEvent) => {
x.value = event.pageX;
y.value = event.pageY;
}
//页面已经加载完毕了,再进行点击的操作
//页面加载完毕的生命周期组合API
onMounted(()=>{
window.addEventListener('click',clickHandler)
})
//页面加载之前的生命周期组合API
onBeforeUnmount(()=>{
window.removeEventListener('click',clickHandler)
})
return {
x.y
}
}
在需要使用的页面将其引入
import useMousePosition from '位置';
setup() {
const {x,y} = useMousePosition;
return {
x,y
}
}
2、自定一个请求Hook
import {ref} from 'vue';
import axios from 'axios';
export default function (url:string){
const loading=ref(true);
const data = ref(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
}
}