| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 |
- // useRouter.ts
- export default function useRouter() {
- type RouteOptions = string | { path: string; query?: Record<string, any> };
- 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 push = (to: RouteOptions) => {
- const url = normalizeUrl(to);
- uni.navigateTo({ url });
- };
- const replace = (to: RouteOptions) => {
- const url = normalizeUrl(to);
- uni.redirectTo({ url });
- };
- const switchTo = (to: RouteOptions) => {
- const url = normalizeUrl(to);
- uni.switchTab({ url });
- };
- const reLaunch = (to: RouteOptions) => {
- const url = normalizeUrl(to);
- uni.reLaunch({ url });
- };
- const back = (delta: number = 1) => {
- uni.navigateBack({ delta });
- };
- return { push, replace, switchTo, reLaunch, back };
- }
|