vue-hooks__钩子函数
1. 什么是钩子函数
钩子函数是一种在某个时刻被调用的函数,它可以让我们在某个时刻做一些事情,比如在组件挂载之前做一些事情,或者在组件更新之前做一些事情,或者在组件卸载之前做一些事情。
2. 常用钩子函数
- useTime 日期时间
import { ref } from "vue";
/**
* @description 获取本地时间
*/
export const useTime = () => {
const year = ref(0); // 年份
const month = ref(0); // 月份
const week = ref(""); // 星期几
const day = ref(0); // 天数
const hour = ref<number | string>(0); // 小时
const minute = ref<number | string>(0); // 分钟
const second = ref<number | string>(0); // 秒
const nowTime = ref<string>(""); // 当前时间
// 更新时间
const updateTime = () => {
const date = new Date();
year.value = date.getFullYear();
month.value = date.getMonth() + 1;
week.value = "日一二三四五六".charAt(date.getDay());
day.value = date.getDate();
hour.value =
(date.getHours() + "")?.padStart(2, "0") ||
new Intl.NumberFormat(undefined, { minimumIntegerDigits: 2 }).format(date.getHours());
minute.value =
(date.getMinutes() + "")?.padStart(2, "0") ||
new Intl.NumberFormat(undefined, { minimumIntegerDigits: 2 }).format(date.getMinutes());
second.value =
(date.getSeconds() + "")?.padStart(2, "0") ||
new Intl.NumberFormat(undefined, { minimumIntegerDigits: 2 }).format(date.getSeconds());
nowTime.value = `${year.value}年${month.value}月${day.value} ${hour.value}:${minute.value}:${second.value}`;
};
updateTime();
return { year, month, day, hour, minute, second, week, nowTime };
};
使用:
import { useTime } from '@/hooks/useTime.js'
const { year, month, day, hour, minute, second, week, nowTime } = useTime();
// 可根据需求使用
// 今天是:{{year}}年{{month}}月{{day}}日 {{hour}}:{{minute}}:{{second}} 星期{{week}},当前时间:{{nowTime}}
- useScroll 监听滚动
import { ref, onMounted, onUnmounted } from "vue";
/**
* @description 监听滚动
*/
export const useScroll = () => {
const scrollX = ref(0); // 滚动条X轴位置
const scrollY = ref(0); // 滚动条Y轴位置
// 监听滚动
const handleScroll = () => {
scrollX.value = window.pageXOffset;
scrollY.value = window.pageYOffset;
};
onMounted(() => {
window.addEventListener("scroll", handleScroll);
});
onUnmounted(() => {
window.removeEventListener("scroll", handleScroll);
});
return { scrollX, scrollY };
};
使用:
import { useScroll } from '@/hooks/useScroll.js'
const { scrollX, scrollY } = useScroll();
// 可根据需求使用
// 滚动条X轴位置:{{scrollX}},滚动条Y轴位置:{{scrollY}}
- useMouse 鼠标位置
import { ref, onMounted, onUnmounted } from "vue";
/**
* @description 鼠标位置
*/
export const useMouse = () => {
const x = ref(0); // 鼠标X轴位置
const y = ref(0); // 鼠标Y轴位置
// 监听鼠标移动
const handleMouseMove = (e: MouseEvent) => {
x.value = e.pageX;
y.value = e.pageY;
};
onMounted(() => {
window.addEventListener("mousemove", handleMouseMove);
});
onUnmounted(() => {
window.removeEventListener("mousemove", handleMouseMove);
});
return { x, y };
};
使用:
import { useMouse } from '@/hooks/useMouse.js'
const { x, y } = useMouse();
// 可根据需求使用
// 鼠标X轴位置:{{x}},鼠标Y轴位置:{{y}}
- useClickAway 点击外部
import { ref, onMounted, onUnmounted } from "vue";
/**
* @description 点击外部
* @param {HTMLElement} element
* @param {Function} callback
*/
export const useClickAway = (element: HTMLElement, callback: Function) => {
const isClickAway = ref(false); // 是否点击外部
// 监听点击
const handleClick = (e: MouseEvent) => {
if (element.contains(e.target as HTMLElement)) {
isClickAway.value = false;
} else {
isClickAway.value = true;
callback();
}
};
onMounted(() => {
window.addEventListener("click", handleClick);
});
onUnmounted(() => {
window.removeEventListener("click", handleClick);
});
return { isClickAway };
};
使用:
import { useClickAway } from '@/hooks/useClickAway.js'
const { isClickAway } = useClickAway(document.body, () => {
console.log("点击外部");
});
// 可根据需求使用
// 是否点击外部:{{isClickAway}}
- useFullscreen 全屏
import { ref, onMounted, onUnmounted } from "vue";
/**
* @description 全屏
* @param {HTMLElement} element
*/
export const useFullscreen = (element: HTMLElement) => {
const isFullscreen = ref(false); // 是否全屏
// 进入全屏
const enterFullscreen = () => {
if (element.requestFullscreen) {
element.requestFullscreen();
} else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if (element.webkitRequestFullscreen) {
element.webkitRequestFullscreen();
} else if (element.msRequestFullscreen) {
element.msRequestFullscreen();
}
};
// 退出全屏
const exitFullscreen = () => {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
}
};
// 监听全屏变化
const handleFullscreenChange = () => {
if (
document.fullscreenElement ||
document.mozFullScreenElement ||
document.webkitFullscreenElement ||
document.msFullscreenElement
) {
isFullscreen.value = true;
} else {
isFullscreen.value = false;
}
};
onMounted(() => {
document.addEventListener("fullscreenchange", handleFullscreenChange);
document.addEventListener("mozfullscreenchange", handleFullscreenChange);
document.addEventListener("webkitfullscreenchange", handleFullscreenChange);
document.addEventListener("MSFullscreenChange", handleFullscreenChange);
});
onUnmounted(() => {
document.removeEventListener("fullscreenchange", handleFullscreenChange);
document.removeEventListener("mozfullscreenchange", handleFullscreenChange);
document.removeEventListener("webkitfullscreenchange", handleFullscreenChange);
document.removeEventListener("MSFullscreenChange", handleFullscreenChange);
});
return { isFullscreen, enterFullscreen, exitFullscreen };
};
使用:
import { useFullscreen } from '@/hooks/useFullscreen.js'
const { isFullscreen, enterFullscreen, exitFullscreen } = useFullscreen(document.body);
// 可根据需求使用
// 是否全屏:{{isFullscreen}}
// 进入全屏:{{enterFullscreen}}
// 退出全屏:{{exitFullscreen}}
- useGeolocation 地理位置
import { ref, onMounted, onUnmounted } from "vue";
/**
* @description 地理位置
*/
export const useGeolocation = () => {
const latitude = ref(0); // 纬度
const longitude = ref(0); // 经度
const accuracy = ref(0); // 精度
const altitude = ref(0); // 海拔
const altitudeAccuracy = ref(0); // 海拔精度
const heading = ref(0); // 方向
const speed = ref(0); // 速度
const timestamp = ref(0); // 时间戳
// 监听地理位置变化
const handleGeolocationChange = (e: Position) => {
latitude.value = e.coords.latitude;
longitude.value = e.coords.longitude;
accuracy.value = e.coords.accuracy;
altitude.value = e.coords.altitude;
altitudeAccuracy.value = e.coords.altitudeAccuracy;
heading.value = e.coords.heading;
speed.value = e.coords.speed;
timestamp.value = e.timestamp;
};
onMounted(() => {
navigator.geolocation.watchPosition(handleGeolocationChange);
});
onUnmounted(() => {
navigator.geolocation.clearWatch(handleGeolocationChange);
});
return {
latitude,
longitude,
accuracy,
altitude,
altitudeAccuracy,
heading,
speed,
timestamp,
};
};
使用:
import { useGeolocation } from '@/hooks/useGeolocation.js'
const { latitude, longitude, accuracy, altitude, altitudeAccuracy, heading, speed, timestamp } = useGeolocation();
// 可根据需求使用
// 纬度:{{latitude}}
// 经度:{{longitude}}
// 精度:{{accuracy}}
// 海拔:{{altitude}}
// 海拔精度:{{altitudeAccuracy}}
// 方向:{{heading}}
// 速度:{{speed}}
// 时间戳:{{timestamp}}
- useGif 图片转换为 gif
import { ref, onMounted, onUnmounted } from "vue";
/**
* @description 图片转换为 gif
* @param {string} src
*/
export const useGif = (src: string) => {
const gif = ref(""); // gif
// 图片转换为 gif
const handleGif = () => {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
const img = new Image();
img.src = src;
img.onload = () => {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
gif.value = canvas.toDataURL("image/gif");
};
};
onMounted(() => {
handleGif();
});
onUnmounted(() => {
gif.value = "";
});
return { gif };
};
使用:
import { useGif } from '@/hooks/useGif.js'
const { gif } = useGif('/i/ll/?i=20201224153605959.png');
// 可根据需求使用
// gif:{{gif}}
标签:__,vue,const,hooks,value,element,import,document,ref
From: https://www.cnblogs.com/miyagi-jiye/p/16793884.html