Application and page lifecycle management functions for initializing UniApp applications and configuring page components with proper lifecycle handling, state management, and routing integration.
Initialize and configure the main application component with lifecycle hooks and global state management.
/**
* Setup a UniApp application component with lifecycle management
* @param comp - Application component definition
* @returns Configured application component
*/
function setupApp(comp: any): DefineComponent;Usage Examples:
import { setupApp } from "@dcloudio/uni-h5";
// Basic app setup
const App = setupApp({
onLaunch() {
console.log('App launched');
// Initialize global data, check login status, etc.
},
onShow() {
console.log('App shown');
// Handle app coming to foreground
},
onHide() {
console.log('App hidden');
// Handle app going to background
},
onError(error) {
console.error('App error:', error);
// Handle global errors
}
});
// App with global data
const App = setupApp({
setup() {
const globalStore = reactive({
user: null,
token: ''
});
return {
globalStore
};
},
onLaunch() {
// Initialize app-level data
this.globalStore.token = uni.getStorageSync('token');
}
});Configure page components with lifecycle hooks, query parameter handling, and page-specific functionality.
/**
* Setup a UniApp page component with lifecycle and navigation support
* @param comp - Page component definition
* @returns Configured page component
*/
function setupPage(comp: any): DefineComponent;Usage Examples:
import { setupPage } from "@dcloudio/uni-h5";
// Basic page setup
const HomePage = setupPage({
setup() {
const data = reactive({
title: 'Home Page',
items: []
});
return {
data
};
},
onLoad(options) {
console.log('Page loaded with options:', options);
// Handle page initialization with query parameters
},
onShow() {
console.log('Page shown');
// Refresh data, update UI
},
onReady() {
console.log('Page ready');
// Page rendering complete
},
onHide() {
console.log('Page hidden');
// Save state, pause operations
},
onUnload() {
console.log('Page unloaded');
// Cleanup resources
},
onPullDownRefresh() {
// Handle pull to refresh
this.refreshData().finally(() => {
uni.stopPullDownRefresh();
});
},
onReachBottom() {
// Handle scroll to bottom
this.loadMoreData();
}
});
// Page with navigation handling
const DetailPage = setupPage({
setup() {
return {
id: ref(''),
data: ref(null)
};
},
onLoad(options) {
this.id = options.id;
this.loadData();
},
methods: {
async loadData() {
try {
const result = await uni.request({
url: `/api/detail/${this.id}`
});
this.data = result.data;
} catch (error) {
uni.showToast({
title: 'Failed to load data',
icon: 'error'
});
}
}
}
});Configure window components for custom windows or sub-windows with specific ID management.
/**
* Setup a window component with ID management
* @param comp - Window component definition
* @param id - Window identifier
* @returns Configured window component
*/
function setupWindow(comp: any, id: number): DefineComponent;Usage Examples:
import { setupWindow } from "@dcloudio/uni-h5";
// Custom window setup
const CustomWindow = setupWindow({
setup() {
return {
content: ref('Custom window content')
};
},
mounted() {
console.log('Custom window mounted with ID:', this.$page.id);
}
}, 1001);Access the current application instance and page stack for global state management and navigation control.
/**
* Get the current application instance
* @returns Current app component instance
*/
function getApp(): ComponentPublicInstance;
/**
* Get the current page stack
* @returns Array of current page instances
*/
function getCurrentPages(): ComponentPublicInstance[];Usage Examples:
import { getApp, getCurrentPages } from "@dcloudio/uni-h5";
// Access global app data
const app = getApp();
console.log('App global data:', app.globalStore);
// Navigate based on page stack
const pages = getCurrentPages();
const currentPage = pages[pages.length - 1];
console.log('Current page route:', currentPage.route);
// Check if can go back
if (pages.length > 1) {
uni.navigateBack();
} else {
uni.reLaunch({
url: '/pages/index/index'
});
}
// Access previous page
if (pages.length > 1) {
const prevPage = pages[pages.length - 2];
prevPage.refreshData?.(); // Call method on previous page
}Built-in framework components for application structure and error handling.
/**
* Main layout component for app structure
*/
export const LayoutComponent: DefineComponent;
/**
* Page wrapper component
*/
export const PageComponent: DefineComponent;
/**
* Async error boundary component
*/
export const AsyncErrorComponent: DefineComponent<{
error?: Error;
}>;
/**
* Async loading component
*/
export const AsyncLoadingComponent: DefineComponent;Usage Examples:
import { LayoutComponent, PageComponent, AsyncErrorComponent, AsyncLoadingComponent } from "@dcloudio/uni-h5";
// Using layout component
const AppLayout = {
template: `
<LayoutComponent>
<router-view />
</LayoutComponent>
`
};
// Using async components
const AsyncPage = defineAsyncComponent({
loader: () => import('./HeavyPage.vue'),
loadingComponent: AsyncLoadingComponent,
errorComponent: AsyncErrorComponent,
delay: 200,
timeout: 3000
});Page and app lifecycle hooks for managing component states and data flow.
// App lifecycle hooks
interface AppLifecycle {
onLaunch?(options: LaunchOptions): void;
onShow?(options: ShowOptions): void;
onHide?(): void;
onError?(error: string): void;
onPageNotFound?(options: PageNotFoundOptions): void;
onUnhandledRejection?(options: UnhandledRejectionOptions): void;
onThemeChange?(options: ThemeChangeOptions): void;
}
// Page lifecycle hooks
interface PageLifecycle {
onLoad?(options: Record<string, string>): void;
onShow?(): void;
onReady?(): void;
onHide?(): void;
onUnload?(): void;
onPullDownRefresh?(): void;
onReachBottom?(): void;
onTabItemTap?(options: TabItemTapOptions): void;
onShareAppMessage?(options: ShareAppMessageOptions): ShareAppMessageResult;
onShareTimeline?(): ShareTimelineResult;
onAddToFavorites?(options: AddToFavoritesOptions): AddToFavoritesResult;
onPageScroll?(options: PageScrollOptions): void;
onResize?(options: ResizeOptions): void;
}
// Lifecycle option types
interface LaunchOptions {
path: string;
query: Record<string, any>;
scene: number;
shareTicket?: string;
referrerInfo?: ReferrerInfo;
}
interface ShowOptions {
path: string;
query: Record<string, any>;
scene: number;
shareTicket?: string;
referrerInfo?: ReferrerInfo;
}
interface PageNotFoundOptions {
path: string;
query: Record<string, any>;
isEntryPage: boolean;
}
interface TabItemTapOptions {
index: number;
pagePath: string;
text: string;
}
interface PageScrollOptions {
scrollTop: number;
}
interface ResizeOptions {
size: {
windowWidth: number;
windowHeight: number;
};
}interface ComponentPublicInstance {
$el: Element;
$data: Record<string, any>;
$props: Record<string, any>;
$attrs: Record<string, any>;
$refs: Record<string, any>;
$slots: Record<string, any>;
$root: ComponentPublicInstance;
$parent: ComponentPublicInstance | null;
$emit: (event: string, ...args: any[]) => void;
$nextTick: typeof nextTick;
$watch: typeof watch;
$forceUpdate: () => void;
// UniApp specific
$page?: PageInstance;
$pageInstance?: ComponentPublicInstance;
route?: string;
options?: Record<string, any>;
}
interface PageInstance {
id: number;
route: string;
options: Record<string, any>;
$page: {
id: number;
route: string;
options: Record<string, any>;
};
$vm?: ComponentPublicInstance;
}
interface DefineComponent<Props = {}> {
new (): ComponentPublicInstance & Props;
__vccOpts: any;
}
interface ReferrerInfo {
appId: string;
extraData?: Record<string, any>;
}
interface ShareAppMessageResult {
title?: string;
path?: string;
imageUrl?: string;
success?: () => void;
fail?: () => void;
complete?: () => void;
}
interface ShareTimelineResult {
title?: string;
query?: string;
imageUrl?: string;
success?: () => void;
fail?: () => void;
complete?: () => void;
}
interface AddToFavoritesResult {
title?: string;
imageUrl?: string;
query?: string;
success?: () => void;
fail?: () => void;
complete?: () => void;
}