| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- // useRouter.ts
- export default function useRouter() {
- type RouteOptions = string | {
- path: string;
- query?: Record<string, any>;
- animationType?: 'slide-in-right' | 'slide-in-left' | 'slide-in-top' | 'slide-in-bottom' |
- 'fade-in' | 'zoom-in' | 'pop-in' | 'none';
- animationDuration?: number;
- };
- const normalizeUrl = (to: RouteOptions) => {
- if (typeof to === 'string') return to;
- if (typeof to === 'object' && to.path) {
- let url = to.path;
- if (to.query && Object.keys(to.query).length) {
- const queryStr = Object.keys(to.query)
- .map(key => `${key}=${encodeURIComponent(to.query![key])}`)
- .join('&');
- url += `?${queryStr}`;
- }
- console.log(url, 'urlurlurl');
- return url;
- }
- throw new Error('[useRouter] Invalid route: ' + JSON.stringify(to));
- };
- // 获取动画配置,默认使用淡入动画
- const getAnimationOptions = (to: RouteOptions) => {
- // 默认动画:淡入,时长300ms
- const defaultAnimation = {
- animationType: 'fade-in',
- animationDuration: 3000
- };
- // 如果传入的是字符串,使用默认动画
- if (typeof to === 'string') {
- return defaultAnimation;
- }
- // 如果传入的是对象且没有指定动画类型,使用默认动画
- if (typeof to === 'object') {
- return {
- animationType: to.animationType || defaultAnimation.animationType,
- animationDuration: to.animationDuration || defaultAnimation.animationDuration
- };
- }
- return defaultAnimation;
- };
- const push = (to: RouteOptions) => {
- const url = normalizeUrl(to);
- const animation = getAnimationOptions(to);
- uni.navigateTo({
- url,
- "animationType": "fade-in", // 全局默认动画
- "animationDuration": 300 // 全局动画时长
- });
- };
- const replace = (to: RouteOptions) => {
- const url = normalizeUrl(to);
- const animation = getAnimationOptions(to);
- uni.redirectTo({
- url,
- ...animation
- });
- };
- const switchTo = (to: RouteOptions) => {
- const url = normalizeUrl(to);
- // switchTab 不支持动画
- uni.switchTab({ url });
- };
- const reLaunch = (to: RouteOptions) => {
- const url = normalizeUrl(to);
- // reLaunch 不支持动画
- uni.reLaunch({ url });
- };
- const back = (delta: number = 1, options?: { animationType?: string; animationDuration?: number }) => {
- if (options) {
- uni.navigateBack({
- delta,
- ...options
- });
- } else {
- uni.navigateBack({ delta })
- }
- };
- return { push, replace, switchTo, reLaunch, back };
- }
|