### Initialize and Get Service Provider with useProvider (TypeScript) Source: https://github.com/uni-helper/uni-use/blob/main/src/useProvider/index.md This snippet demonstrates how to import and use the `useProvider` hook from '@uni-helper/uni-use'. It shows the initial setup by passing configuration options and then calling the returned function to obtain the service provider. No external dependencies are required beyond the '@uni-helper/uni-use' package. ```typescript import { useProvider } from '@uni-helper/uni-use'; const getProvider = useProvider({ /* 传入配置 */ }); getProvider(); // 获取服务供应商 ``` -------------------------------- ### Install uni-use with npm Source: https://github.com/uni-helper/uni-use/blob/main/docs/guide/index.md Installs the uni-use package and @vueuse/core version 9. If you need to use @vueuse/core v10+, you may need to provide polyfills or use vite-plugin-uni-polyfill. Specific instructions for yarn v2+ and pnpm are also provided. ```bash npm install @uni-helper/uni-use @vueuse/core@9 ``` -------------------------------- ### Get hideLoading from showLoading Source: https://github.com/uni-helper/uni-use/blob/main/src/useLoading/index.md This example illustrates an alternative way to obtain the `hideLoading` function by calling `showLoading`. This can be useful for scenarios where the hide function is needed directly after initiating the loading state. ```typescript import { useLoading } from '@uni-helper/uni-use'; const { showLoading, hideLoading } = useLoading({ /* 传入配置 */ }); const hideLoading = showLoading(); ``` -------------------------------- ### Get All Page Parameters with useQuery Source: https://github.com/uni-helper/uni-use/blob/main/src/useQuery/index.md Retrieve all query parameters passed to the current page. This is the basic usage of the useQuery composable. The returned 'query' is a ref containing an object of all parameters. ```vue import { useQuery } from '@uni-helper/uni-use'; // Get all page parameters const { query } = useQuery(); // Example navigation: // uni.navigateTo({ url: '/pages/detail?id=123&name=test' }) // query.value will be { id: '123', name: 'test' } ``` -------------------------------- ### Polyfills for uni-app with core-js Source: https://github.com/uni-helper/uni-use/blob/main/README.md Adds necessary polyfills for uni-app projects using Vue 3, specifically for features like array iterators, promises, and object assignment. This example uses 'core-js' and assumes it has been installed separately. Other polyfill solutions like 'es-shims' can also be used. ```typescript // You can add extra polyfills as needed // import 'core-js/actual/object/values' import { createSSRApp } from 'vue'; import App from './App.vue'; import 'core-js/actual/array/iterator'; import 'core-js/actual/promise'; import 'core-js/actual/object/assign'; import 'core-js/actual/promise/finally'; export function createApp() { const app = createSSRApp(App); return { app, }; } ``` -------------------------------- ### Integrate uni-use with unplugin-auto-import Source: https://github.com/uni-helper/uni-use/blob/main/docs/guide/index.md Shows how to configure vite.config.ts to integrate uni-use with unplugin-auto-import. This setup enables automatic importing of uni-use utilities, simplifying their usage in your uni-app project. ```typescript // vite.config.ts import { fileURLToPath } from 'node:url'; import uni from '@dcloudio/vite-plugin-uni'; import { uniuseAutoImports } from '@uni-helper/uni-use'; import autoImport from 'unplugin-auto-import/vite'; import { defineConfig } from 'vitest/config'; // https://vitejs.dev/config/ export default defineConfig({ plugins: [ autoImport({ imports: [ uniuseAutoImports(), ], }), uni({ /* ... */ }), ], }); ``` -------------------------------- ### Polyfill Setup for Vue 3 Main Entry Point Source: https://github.com/uni-helper/uni-use/blob/main/docs/guide/notice.md This code snippet shows how to add polyfills to your Vue 3 application's main entry point (main.ts or main.js) when using uni-app. It imports necessary polyfills from 'core-js' for array iterators, promises, object assignment, and promise finally. You can customize these imports based on your project's specific needs and the compatibility requirements of your target environments. ```typescript // 你可以根据需要自行添加额外的 polyfills // import 'core-js/actual/object/values' import { createSSRApp } from 'vue'; import App from './App.vue'; import 'core-js/actual/array/iterator'; import 'core-js/actual/promise'; import 'core-js/actual/object/assign'; import 'core-js/actual/promise/finally'; export function createApp() { const app = createSSRApp(App); return { app, }; } ``` -------------------------------- ### Get Previous Route Information with TypeScript Source: https://github.com/uni-helper/uni-use/blob/main/src/usePrevRoute/index.md This snippet demonstrates how to import and use the `usePrevRoute` composable in TypeScript to retrieve the previous page's route details. It requires the `@uni-helper/uni-use` package. ```typescript import { usePrevRoute } from '@uni-helper/uni-use'; const prevRoute = usePrevRoute(); ``` -------------------------------- ### Get and Set Clipboard Data with useClipboardData (TypeScript) Source: https://github.com/uni-helper/uni-use/blob/main/src/useClipboardData/index.md This snippet demonstrates the basic usage of the `useClipboardData` hook to initialize, read, and set clipboard data. It takes an initial value and allows access to the clipboard content via a ref. ```typescript import { useClipboardData } from '@uni-helper/uni-use'; const clipboardData = useClipboardData(''); // 查看剪切板数据 console.log('clipboardData', clipboardData.value); // 设置剪切板数据 clipboardData.value = 'abc'; ``` -------------------------------- ### Get Specific Page Parameter with useQuery Source: https://github.com/uni-helper/uni-use/blob/main/src/useQuery/index.md Fetch the value of a specific query parameter by providing its key to the useQuery function. The 'value' returned is a ref that holds the parameter's value. ```vue import { useQuery } from '@uni-helper/uni-use'; // Get specific parameter values const { value: userId } = useQuery('id'); const { value: userName } = useQuery('name'); // Example navigation: // uni.navigateTo({ url: '/pages/detail?id=123&name=test' }) // userId.value will be '123' // userName.value will be 'test' ``` -------------------------------- ### Setup and Remove Interceptor with useInterceptor (TypeScript) Source: https://github.com/uni-helper/uni-use/blob/main/src/useInterceptor/index.md This snippet demonstrates how to use the useInterceptor function to set up and remove an event interceptor. It shows how to modify arguments, handle success and failure callbacks, and use the returned stop function to unregister the interceptor. The interceptor can be halted if the invoke function returns false. ```typescript import { useInterceptor } from '@uni-helper/uni-use'; const event = 'request'; // 设置拦截器 const stop = useInterceptor(event, { invoke: (args) => { args[0].url = `https://www.example.com/${args[0].url}`; }, success: (response) => { console.log('interceptor-success', response); response.data.code = 1; }, fail: (error) => { console.log('interceptor-fail', error); }, complete: () => { console.log('interceptor-complete'); }, }); // 删除拦截器 stop(); ``` -------------------------------- ### Get Previous Page Information with TypeScript Source: https://github.com/uni-helper/uni-use/blob/main/src/usePrevPage/index.md This snippet demonstrates how to import and use the usePrevPage hook to retrieve information about the preceding page. It requires the @uni-helper/uni-use library. The hook returns information about the previous page, which can be utilized for various navigation-related functionalities. ```typescript import { usePrevPage } from '@uni-helper/uni-use'; const prevPage = usePrevPage(); ``` -------------------------------- ### Synchronous Storage Operation with useStorageSync (TypeScript) Source: https://github.com/uni-helper/uni-use/blob/main/src/useStorageSync/index.md Demonstrates how to use useStorageSync to synchronously set and get values from uni-app's storage. This function is suitable for immediate data persistence but will block the thread until the operation completes. It takes a key and an initial value as arguments. ```typescript import { useStorageSync } from '@uni-helper/uni-use'; const token = useStorageSync('authorization', ''); // Assignment token.value = 'authorization-token'; // Reading console.log(token.value); // authorization-token ``` -------------------------------- ### Display and Hide Toast Messages with useToast (TypeScript) Source: https://github.com/uni-helper/uni-use/blob/main/src/useToast/index.md This snippet demonstrates how to import and use the `useToast` hook to display and hide toast messages. It shows the initial setup and how to call the returned functions. Configuration options can be passed during initialization. ```typescript import { useToast } from '@uni-helper/uni-use'; const showToast = useToast({ /* 传入配置 */ }); const hideToast = showToast(); // 显示消息提示框 hideToast(); // 隐藏消息提示框 ``` -------------------------------- ### Get and Set Screen Brightness with Default Value - TypeScript Source: https://github.com/uni-helper/uni-use/blob/main/src/useScreenBrightness/index.md Demonstrates how to initialize and use the useScreenBrightness hook with a default brightness value. It shows how to access the current brightness and how to set a new brightness level. The hook is imported from '@uni-helper/uni-use'. ```typescript import { useScreenBrightness } from '@uni-helper/uni-use'; const screenBrightness = useScreenBrightness(1); // 查看屏幕亮度 console.log('screenBrightness', screenBrightness.value); // 设置屏幕亮度 screenBrightness.value = 0; ``` -------------------------------- ### usePrevPage - Get Previous Page Instance Source: https://context7.com/uni-helper/uni-use/llms.txt Returns a reactive reference to the previous page's instance in the navigation stack. This hook is useful for interacting with the preceding page, such as calling its methods or accessing its data. It relies on uni-app's page navigation context. ```typescript import { usePrevPage } from '@uni-helper/uni-use' const prevPage = usePrevPage() // Access previous page information console.log('Previous page route:', prevPage.value?.route) // Call previous page methods if (prevPage.value) { prevPage.value.$vm.refreshList() } ``` -------------------------------- ### Get Current Page Stack Information with TypeScript Source: https://github.com/uni-helper/uni-use/blob/main/src/usePages/index.md This snippet demonstrates how to import and use the `usePages` hook in a TypeScript environment. It retrieves the current page stack, which can be an array of page objects. No specific dependencies are required beyond the `@uni-helper/uni-use` package. ```typescript import { usePages } from '@uni-helper/uni-use'; const pages = usePages(); ``` -------------------------------- ### useQuery - Get Current Route Query Parameters Source: https://context7.com/uni-helper/uni-use/llms.txt Provides a reactive reference to the current page's query parameters. This hook simplifies accessing and reacting to changes in URL query strings. It is particularly useful for fetching data based on parameters or dynamically updating the UI. Dependencies include uni-app's routing system. ```typescript import { useQuery } from '@uni-helper/uni-use' // Access all parameters const query = useQuery() console.log('All parameters:', query.value) // Access specific parameters const id = computed(() => query.value.id) const type = computed(() => query.value.type) // Watch for parameter changes watch(query, (params) => { console.log('Parameters updated:', params) fetchData(params) }) ``` -------------------------------- ### usePrevRoute - Get Previous Route Information Source: https://context7.com/uni-helper/uni-use/llms.txt Provides a reactive reference to the previous route's information. This hook is helpful for determining the origin of navigation and implementing conditional logic based on where the user came from. It accesses uni-app's navigation history. ```typescript import { usePrevRoute } from '@uni-helper/uni-use' const prevRoute = usePrevRoute() // Access previous route console.log('Source page:', prevRoute.value) // Conditional logic if (prevRoute.value === '/pages/cart/cart') { showCheckoutHint.value = true } ``` -------------------------------- ### Get Current Route Information with TypeScript Source: https://github.com/uni-helper/uni-use/blob/main/src/useRoute/index.md This snippet demonstrates how to import and use the useRoute hook from '@uni-helper/uni-use' in a TypeScript environment. It retrieves the current route object, which can then be used to access properties like path, query parameters, and route metadata. No external dependencies beyond the library itself are required. ```typescript import { useRoute } from '@uni-helper/uni-use'; const route = useRoute(); ``` -------------------------------- ### useRoute - Get Current Route Information Source: https://context7.com/uni-helper/uni-use/llms.txt Returns a reactive reference to the current page's route information, including the path, query parameters, and other route details. This hook is crucial for accessing navigation context and implementing route-specific logic. It relies on uni-app's router. ```typescript import { useRoute } from '@uni-helper/uni-use' const route = useRoute() // Access route information console.log('Current path:', route.path) console.log('Route query:', route.query) // Watch for route changes watch(() => route.query.id, (id) => { console.log('ID parameter changed:', id) loadDetail(id) }) // Conditional rendering const isDetailPage = computed(() => { return route.path.includes('/detail') }) ``` -------------------------------- ### Get Network Information with TypeScript - useNetwork Source: https://github.com/uni-helper/uni-use/blob/main/src/useNetwork/index.md This snippet demonstrates how to import and use the useNetwork hook from the '@uni-helper/uni-use' library in TypeScript. It destructures various network status properties, including connection type and specific band statuses (2G, 3G, 4G, 5G), as well as general online/offline states. No external dependencies beyond the library itself are required for basic usage. ```typescript import { useNetwork } from '@uni-helper/uni-use'; const { type, isWifi, is2g, is3g, is4g, is5g, isEthernet, isUnknown, isOnline, isOffline } = useNetwork(); ``` -------------------------------- ### Scenario: Product Detail Page Navigation and Reception Source: https://github.com/uni-helper/uni-use/blob/main/src/useQuery/index.md Illustrates passing product details as a JSON string via `encodeURIComponent` and `JSON.stringify` during navigation, and how to receive and parse it on the detail page using `useQuery`. ```javascript // Product List Page Navigation const product = { id: 'P001', name: '商品A', price: 99.99 }; uni.navigateTo({ url: `/pages/product/detail?product=${encodeURIComponent(JSON.stringify(product))}` }); // Product Detail Page Reception // import { useQuery } from '@uni-helper/uni-use'; // const { value: productInfo } = useQuery('product'); // productInfo.value will be { id: 'P001', name: '商品A', price: 99.99 } ``` -------------------------------- ### Scenario: Order Page Navigation and Reception Source: https://github.com/uni-helper/uni-use/blob/main/src/useQuery/index.md Demonstrates passing complex order data as a JSON string during navigation and receiving it on the order creation page. Uses `JSON.stringify` for passing the data. ```javascript // Order Creation Page Navigation const orderData = { items: [{ id: 1, qty: 2 }], total: 198, userId: 'U001' }; uni.navigateTo({ url: `/pages/order/create?data=${JSON.stringify(orderData)}` }); // Order Creation Page Reception // import { useQuery } from '@uni-helper/uni-use'; // const { value: order } = useQuery('data'); // order.value will be { items: [{ id: 1, qty: 2 }], total: 198, userId: 'U001' } ``` -------------------------------- ### Basic Usage of tryOnLoad in uni-app Source: https://github.com/uni-helper/uni-use/blob/main/docs/guide/index.md Demonstrates the basic usage of the tryOnLoad function from @uni-helper/uni-use. This function allows you to execute code when the component's onLoad lifecycle hook is triggered in uni-app. ```typescript import { tryOnLoad } from '@uni-helper/uni-use'; tryOnLoad(() => { console.log('onLoad'); }); ``` -------------------------------- ### Initialize and Use useLoading Hook Source: https://github.com/uni-helper/uni-use/blob/main/src/useLoading/index.md This snippet demonstrates how to import and initialize the `useLoading` hook from '@uni-helper/uni-use'. It shows the basic usage of calling `showLoading` to display a loading indicator and `hideLoading` to dismiss it. Configuration options can be passed during initialization. ```typescript import { useLoading } from '@uni-helper/uni-use'; const { showLoading, hideLoading } = useLoading({ /* 传入配置 */ }); showLoading(); // 显示加载提示框 hideLoading(); // 隐藏加载提示框 ``` -------------------------------- ### Get Preferred Language with TypeScript Source: https://github.com/uni-helper/uni-use/blob/main/src/usePreferredLanguage/index.md This snippet demonstrates how to import and use the `usePreferredLanguage` composable in a TypeScript environment. It returns the user's preferred language as a string, which can be utilized for internationalization. ```typescript import { usePreferredLanguage } from '@uni-helper/uni-use'; const language = usePreferredLanguage(); ``` -------------------------------- ### Recommended JSON Stringification for Navigation Source: https://github.com/uni-helper/uni-use/blob/main/src/useQuery/index.md Demonstrates the recommended method for passing JSON data as a query parameter using `encodeURIComponent` and `JSON.stringify`. This ensures proper encoding for URL transmission. ```javascript // Navigation const data = { id: 123, name: 'test', details: { amount: 50 } }; uni.navigateTo({ url: `/pages/detail?resData=${encodeURIComponent(JSON.stringify(data))}` }); // Receiving page auto-parses: // const { value: resData } = useQuery('resData'); // resData.value = { id: 123, name: 'test', details: { amount: 50 } } ``` -------------------------------- ### Scenario: Mixed Parameters Navigation and Reception Source: https://github.com/uni-helper/uni-use/blob/main/src/useQuery/index.md Shows how to combine regular query parameters with JSON-encoded parameters when navigating. `useQuery` can retrieve all parameters, parsing JSON automatically where applicable. ```javascript // Complex Page Navigation const complexData = { config: { theme: 'dark' }, user: { role: 'admin' } }; uni.navigateTo({ url: `/pages/dashboard?id=123&source=menu&config=${encodeURIComponent(JSON.stringify(complexData))}` }); // Receiving Page Reception // import { useQuery } from '@uni-helper/uni-use'; // const { query } = useQuery(); // query.value will be { // id: '123', // source: 'menu', // config: { config: { theme: 'dark' }, user: { role: 'admin' } } // } ``` -------------------------------- ### Disable Toast Notification with useClipboardData (TypeScript) Source: https://github.com/uni-helper/uni-use/blob/main/src/useClipboardData/index.md This example shows how to use the `useClipboardData` hook while disabling the default toast message that appears after setting clipboard data. This is achieved by passing an options object with `showToast: false`. ```typescript import { useClipboardData } from '@uni-helper/uni-use'; const clipboardData = useClipboardData('', { showToast: false }); ``` -------------------------------- ### Uni-Use useRouter Hook Usage in TypeScript Source: https://github.com/uni-helper/uni-use/blob/main/src/useRouter/index.md Demonstrates how to import and use the useRouter hook in a TypeScript UniApp project. It covers configuring tabBar navigation and performing various routing actions like switchTab, navigate, redirect, reLaunch, and back. Dependencies include @uni-helper/uni-use and the project's pages.json configuration. ```typescript import { useRouter } from '@uni-helper/uni-use'; import { tabBar } from '@/pages.json'; const router = useRouter({ /** * 是否尝试跳转 tabBar * 开启后,使用 navigate / redirect 将会先尝试 tabBar * @default true */ tryTabBar: true, /** * pages.json 里的 tabBar list 配置 * tryTabBar 开启时,会判断跳转页面 * 全局配置,仅需要配置一次 */ tabBarList: tabBar.list, }); // 如果上面的 tryTabBar 设定为 false,或非常确定是 tabbar 页面,可以直接使用 switchTab router.switchTab({ url: '/pages/tabbar/tabbar1' }); // 路由跳转,参数和 uniapp 的一致 // 当 tryTabBar = true 时,会自动判断 tabBar 页面进行跳转 router.navigate({ url: '/pages/topics/index' }); // 路由重定向,参数和 uniapp 的一致 // 当 tryTabBar = true 时,会自动判断 tabBar 页面进行重定向 router.redirect({ url: '/pages/auth/login' }); // 路由重定向,并清空当前页面栈 router.reLaunch({ url: '/pages/auth/login' }); // 后退 router.back(); ``` -------------------------------- ### tryOnInit - Safe onInit Lifecycle Hook with Retry Source: https://context7.com/uni-helper/uni-use/llms.txt Safely registers the `onInit` lifecycle hook with an optional retry mechanism. This ensures that initialization logic runs reliably, even if there are transient issues. It accepts a callback function and retry options. ```typescript import { tryOnInit } from '@uni-helper/uni-use' tryOnInit(() => { console.log('页面初始化') initializeApp() }, undefined, { retry: 3, interval: 500 }) ``` -------------------------------- ### Initialize and Show Modal with TypeScript Source: https://github.com/uni-helper/uni-use/blob/main/src/useModal/index.md This snippet demonstrates how to import and use the useModal hook from '@uni-helper/uni-use'. It initializes the modal with configuration options and then calls the returned function to display the modal. The hook simplifies modal management in a TypeScript environment. ```typescript import { useModal } from '@uni-helper/uni-use'; const showModal = useModal({ /* 传入配置 */ }); showModal(); // 显示模态弹窗 ``` -------------------------------- ### Initialize and Show Action Sheet with TypeScript Source: https://github.com/uni-helper/uni-use/blob/main/src/useActionSheet/index.md This snippet demonstrates how to import and use the `useActionSheet` hook from '@uni-helper/uni-use'. It initializes the hook with optional configurations and then calls the returned function to display the action sheet. The initial configuration object is optional. ```typescript import { useActionSheet } from '@uni-helper/uni-use'; const showActionSheet = useActionSheet({ /* 传入配置 */ }); showActionSheet(); // 从底部向上弹出操作菜单 ``` -------------------------------- ### Get Current Page Info with TypeScript Source: https://github.com/uni-helper/uni-use/blob/main/src/usePage/index.md The `usePage` function, imported from `@uni-helper/uni-use`, retrieves information about the current page. It requires no arguments and returns a page object. This is useful for accessing page-specific data or lifecycle hooks within your Uni-app components. ```typescript import { usePage } from '@uni-helper/uni-use'; const page = usePage(); ``` -------------------------------- ### Responsive Parameter Keys with useQuery Source: https://github.com/uni-helper/uni-use/blob/main/src/useQuery/index.md Use reactive references for parameter keys to dynamically change which query parameter is being tracked. The 'value' ref will automatically update when the key changes. ```vue import { useQuery } from '@uni-helper/uni-use'; import { ref } from 'vue'; const paramKey = ref('id'); const { value } = useQuery(paramKey); // Dynamically change the parameter key paramKey.value = 'name'; // 'value' will automatically update to the value of the 'name' parameter ``` -------------------------------- ### useRouter - 路由导航增强 Source: https://context7.com/uni-helper/uni-use/llms.txt 封装 uni-app 路由 API,提供 Promise 化的路由跳转、自动 TabBar 判断、页面栈管理等功能。支持 navigate, redirect, back, reLaunch 等多种导航方式。 ```typescript import { useRouter } from '@uni-helper/uni-use' // 初始化路由 - 配置 TabBar 列表 const router = useRouter({ tryTabBar: true, // 自动判断 TabBar 页面 tabBarList: [ { pagePath: '/pages/index/index' }, { pagePath: '/pages/user/user' } ] }) // 页面跳转 - 自动处理 TabBar await router.navigate({ url: '/pages/detail/detail?id=123' }) // 如果是 TabBar 页面,自动使用 switchTab await router.navigate({ url: '/pages/index/index' }) // 路由重定向 await router.redirect({ url: '/pages/login/login' }) // 返回上一页 await router.back({ delta: 1 }) // 重启应用 await router.reLaunch({ url: '/pages/index/index' }) // 访问页面栈信息 console.log('当前页面:', router.current.value?.route) console.log('前一页面:', router.prev.value?.route) console.log('当前路由:', router.currentUrl.value) console.log('页面栈:', router.pages.value) // 监听路由变化 watch(router.currentUrl, (url) => { console.log('路由已切换到:', url) }) ``` -------------------------------- ### Check Online Status with TypeScript - useOnline Source: https://github.com/uni-helper/uni-use/blob/main/src/useOnline/index.md This snippet demonstrates how to use the `useOnline` hook to get the current online status. It imports the hook from '@uni-helper/uni-use' and assigns the boolean result to the `isOnline` constant. This hook is dependent on `useNetwork` to function. ```typescript import { useOnline } from '@uni-helper/uni-use'; const isOnline = useOnline(); ``` -------------------------------- ### Get Page Visibility State with TypeScript - useVisible Source: https://github.com/uni-helper/uni-use/blob/main/src/useVisible/index.md This snippet demonstrates how to import and use the useVisible hook from the '@uni-helper/uni-use' library in TypeScript. It returns a boolean value indicating whether the current page is visible. No external dependencies are required beyond the library itself. ```typescript import { useVisible } from '@uni-helper/uni-use'; const isVisible = useVisible(); ``` -------------------------------- ### Vite Configuration for Uni-App with Vue 3 Source: https://github.com/uni-helper/uni-use/blob/main/docs/guide/notice.md This configuration snippet demonstrates how to set up Vite for a Vue 3 project using uni-app. It includes setting the build target to 'es6' and CSS target, excluding 'vue-demi' from optimizeDeps, and adding the uni() plugin. Ensure your project's build target is compatible with the required JavaScript features. ```typescript import uni from '@dcloudio/vite-plugin-uni'; import { defineConfig } from 'vite'; // https://vitejs.dev/config/ export default defineConfig({ build: { target: 'es6', cssTarget: 'chrome61', // https://cn.vitejs.dev/config/build-options.html#build-csstarget }, optimizeDeps: { exclude: ['vue-demi'], }, plugins: [ // ..., uni(), // ..., ], }); ``` -------------------------------- ### useScreenBrightness - Screen Brightness Control Source: https://context7.com/uni-helper/uni-use/llms.txt Provides a reactive interface to get and set the screen brightness. It returns a reactive reference to the current brightness level, which can be read and modified. Values range from 0 to 1. This hook utilizes system-level APIs. ```typescript import { useScreenBrightness } from '@uni-helper/uni-use' const { brightness } = useScreenBrightness() // Read brightness console.log('Current brightness:', brightness.value) // Set brightness (0-1)rightness.value = 0.8 // Auto adjustment for night mode const hour = new Date().getHours() if (hour >= 22 || hour < 6) { brightness.value = 0.3 } // Adjust based on scenario watch(currentPage, (page) => { if (page === '/pages/reading/reading') { brightness.value = 0.5 // Lower brightness for reading mode } }) ``` -------------------------------- ### Async Storage Management with useStorage in TypeScript Source: https://github.com/uni-helper/uni-use/blob/main/src/useStorage/index.md Demonstrates how to use the `useStorage` composable to manage asynchronous storage. It initializes a storage key 'authorization' with an empty string default value, allows updating the value, and shows how to read the current value. This function is asynchronous, meaning changes are reflected in the ref immediately but written to storage later. ```typescript import { useStorage } from '@uni-helper/uni-use'; const token = useStorage('authorization', ''); // Assign value token.value = 'authorization-token'; // Read value console.log(token.value); // authorization-token ``` -------------------------------- ### Control and Monitor Page Scroll with usePageScroll (TypeScript) Source: https://github.com/uni-helper/uni-use/blob/main/src/usePageScroll/index.md This snippet demonstrates how to use the `usePageScroll` hook to get the current scroll position of the page. It takes an options object, where `onPageScroll` can be set to `true` to enable listening to scroll events. The hook returns an object containing `scrollTop`. ```typescript import { usePageScroll } from '@uni-helper/uni-use'; const { scrollTop } = usePageScroll({ onPageScroll: true, }); ``` -------------------------------- ### Direct JSON Stringification for Navigation Source: https://github.com/uni-helper/uni-use/blob/main/src/useQuery/index.md Shows how to pass JSON data as a query parameter using only `JSON.stringify`. This method might require additional handling if the JSON contains special characters that conflict with URL parsing. ```javascript // Navigation const params = { order: 'A001', type: 'recruitment' }; uni.navigateTo({ url: `/pages/order?data=${JSON.stringify(params)}` }); // Receiving page auto-parses: // const { value: orderData } = useQuery('data'); // orderData.value = { order: 'A001', type: 'recruitment' } ``` -------------------------------- ### useDownloadFile - File Download with Progress Source: https://context7.com/uni-helper/uni-use/llms.txt Provides a reactive interface for downloading files, supporting progress monitoring and manual/automatic download initiation. It returns download progress, status, and the temporary file path upon successful completion. Dependencies include uni-app's network APIs. ```typescript import { useDownloadFile } from '@uni-helper/uni-use' // Auto download const { data, progress, isDownloading } = useDownloadFile( 'https://example.com/file.pdf' ) watch(progress, (p) => { console.log(`Download progress: ${p}%`) }) watch(data, (result) => { if (result) { console.log('File saved to:', result.tempFilePath) } }) // Manual download const { execute, progress, abort } = useDownloadFile({ immediate: false, onSuccess: (res) => { uni.showToast({ title: 'Download complete' }) } }) await execute('https://example.com/document.pdf') ``` -------------------------------- ### usePage - Get Current Page Instance Source: https://context7.com/uni-helper/uni-use/llms.txt Returns a reactive reference to the current page instance, allowing access to page properties and methods. This hook is useful for interacting with the page lifecycle or invoking page-specific functions. It leverages uni-app's page context. ```typescript import { usePage } from '@uni-helper/uni-use' const page = usePage() // Access page information console.log('Page route:', page.value?.route) console.log('Page options:', page.value?.options) // Invoke page methods if (page.value) { page.value.$vm.refreshData() } ``` -------------------------------- ### useStorage - Responsive Local Storage Source: https://context7.com/uni-helper/uni-use/llms.txt Provides responsive asynchronous local caching functionality, automatically synchronizing ref variables with uni.storage. Supports deep watching, type serialization, and storage change listening. ```APIDOC ## useStorage - Responsive Local Storage ### Description Provides responsive asynchronous local caching functionality, automatically synchronizing ref variables with uni.storage. Supports deep watching, type serialization, and storage change listening. ### Method Composition API function ### Endpoint N/A (Client-side function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { useStorage } from '@uni-helper/uni-use' // Basic usage - string storage const username = useStorage('username', 'default-user') username.value = 'john' // Automatically writes to storage // Object storage - automatic serialization const userInfo = useStorage('user-info', { name: '张三', age: 25, preferences: { theme: 'dark' } }) userInfo.value.age = 26 // Automatically serializes and writes // Advanced configuration - merging defaults const settings = useStorage('app-settings', { volume: 50, brightness: 80 }, { mergeDefaults: true, // Shallow merge with stored value deep: true, // Deeply watch object changes listenToStorageChanges: true, // Listen for storage changes elsewhere onError: (err) => console.error('Storage failed:', err) } ) // Set/Map storage const visitedPages = useStorage('visited', new Set()) visitedPages.value.add('/pages/index') // Manual control const token = useStorage('auth-token', '') token.sync() // Manually write to storage token.refresh() // Read from storage again ``` ### Response #### Success Response (200) N/A (This is a composition function, not an API endpoint) #### Response Example N/A ``` -------------------------------- ### Update useLoading Configuration Source: https://github.com/uni-helper/uni-use/blob/main/src/useLoading/index.md This code snippet shows how to update the existing configuration of the `useLoading` hook by passing a new configuration object to `showLoading`. It utilizes the spread syntax to merge new configurations with existing ones. ```typescript showLoading({ /* 新传入配置 */ }); ``` -------------------------------- ### usePages - Get Page Stack Source: https://context7.com/uni-helper/uni-use/llms.txt Provides a reactive reference to the application's page stack, which is an array of all currently active pages. This hook allows you to inspect the navigation history, determine the number of open pages, and react to changes in the stack. It is based on uni-app's navigation state. ```typescript import { usePages } from '@uni-helper/uni-use' const pages = usePages() // Access page stack console.log('Page stack length:', pages.value.length) console.log('All pages:', pages.value.map(p => p.route)) // Determine if navigation back is possible const canGoBack = computed(() => pages.value.length > 1) // Watch for page stack changes watch(pages, (stack) => { console.log('Page stack updated, currently', stack.length, 'pages') }) ``` -------------------------------- ### useStorage - 响应式本地存储 Source: https://context7.com/uni-helper/uni-use/llms.txt 提供响应式的异步本地缓存功能,自动同步 ref 变量与 uni.storage 之间的数据。支持深度监听、类型序列化、存储变化监听以及合并默认值等高级配置。 ```typescript import { useStorage } from '@uni-helper/uni-use' // 基础用法 - 字符串存储 const username = useStorage('username', 'default-user') username.value = 'john' // 自动写入 storage // 对象存储 - 自动序列化 const userInfo = useStorage('user-info', { name: '张三', age: 25, preferences: { theme: 'dark' } }) userInfo.value.age = 26 // 自动序列化并写入 // 高级配置 - 合并默认值 const settings = useStorage('app-settings', { volume: 50, brightness: 80 }, { mergeDefaults: true, // 与存储值浅合并 deep: true, // 深度监听对象变化 listenToStorageChanges: true, // 监听其他地方的存储变化 onError: (err) => console.error('存储失败:', err) } ) // Set/Map 存储 const visitedPages = useStorage('visited', new Set()) visitedPages.value.add('/pages/index') // 手动控制 const token = useStorage('auth-token', '') token.sync() // 手动写入 storage token.refresh() // 从 storage 重新读取 ``` -------------------------------- ### useModal - Modal Dialog Source: https://context7.com/uni-helper/uni-use/llms.txt Returns a function to display modal popups, supporting preset configurations and runtime configuration merging. ```APIDOC ## useModal - Modal Dialog ### Description Returns a function to display modal popups, supporting preset configurations and runtime configuration merging. ### Method Composition API function ### Endpoint N/A (Client-side function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { useModal } from '@uni-helper/uni-use' // Create a pre-configured modal const showConfirm = useModal({ title: 'Confirm action', confirmText: 'Confirm', cancelText: 'Cancel' }) // Use the pre-configured modal to display const result = await showConfirm({ content: 'Are you sure you want to delete this record?' }) if (result.confirm) { console.log('User clicked confirm') } // Dynamically configure modal const showAlert = useModal() await showAlert({ title: 'Tip', content: 'Operation successful', showCancel: false }) // Responsive configuration const modalTitle = ref('Warning') const showWarning = useModal(computed(() => ({ title: modalTitle.value, confirmColor: '#ff0000' }))) modalTitle.value = 'Severe Warning' await showWarning({ content: 'System error' }) ``` ### Response #### Success Response (200) N/A (This is a composition function, not an API endpoint) #### Response Example N/A ``` -------------------------------- ### Execute onLoad with Retry Logic - TypeScript Source: https://github.com/uni-helper/uni-use/blob/main/src/tryOnLoad/index.md The tryOnLoad function attempts to execute the provided callback function, typically used for component initialization. It includes built-in retry logic and handles final execution based on a runFinally callback or throws an error if retry attempts are exhausted. ```typescript import { tryOnLoad } from '@uni-helper/uni-use'; tryOnLoad(() => { // ... }); ``` -------------------------------- ### Usage of tryOnShow in TypeScript Source: https://github.com/uni-helper/uni-use/blob/main/src/tryOnShow/index.md This snippet demonstrates how to import and use the tryOnShow function from the '@uni-helper/uni-use' library in a TypeScript project. It takes a callback function that will be executed when the component's onShow event is triggered. The function includes built-in retry logic and will execute the 'runFinally' callback if retries are exhausted or throw an error. ```typescript import { tryOnShow } from '@uni-helper/uni-use'; tryOnShow(() => { // ... }); ``` -------------------------------- ### useModal - 模态对话框 Source: https://context7.com/uni-helper/uni-use/llms.txt 返回一个用于显示模态弹窗的函数,支持预设配置和运行时配置合并。可以创建预配置的确认/提示框,并支持动态和响应式配置。 ```typescript import { useModal } from '@uni-helper/uni-use' // 创建预配置弹窗 const showConfirm = useModal({ title: '确认操作', confirmText: '确定', cancelText: '取消' }) // 使用预配置显示弹窗 const result = await showConfirm({ content: '确定要删除这条记录吗?' }) if (result.confirm) { console.log('用户点击了确定') } // 动态配置弹窗 const showAlert = useModal() await showAlert({ title: '提示', content: '操作成功', showCancel: false }) // 响应式配置 const modalTitle = ref('警告') const showWarning = useModal(computed(() => ({ title: modalTitle.value, confirmColor: '#ff0000' }))) modalTitle.value = '严重警告' await showWarning({ content: '系统错误' }) ``` -------------------------------- ### tryOnShow - Safely Register onShow Lifecycle Hook Source: https://context7.com/uni-helper/uni-use/llms.txt Safely registers the `onShow` lifecycle hook with retry mechanisms to prevent registration failures when the component instance is not ready. Supports configuration of retry strategies and targeting specific instances. Dependencies: Vue 3. ```typescript import { tryOnShow } from '@uni-helper/uni-use' // Basic usage - automatic retry tryOnShow(() => { console.log('Page shown') refreshData() }) // Configure retry strategy tryOnShow(() => { console.log('Loading data on page show') }, undefined, { retry: 5, // Retry up to 5 times interval: 300, // 300ms interval between retries runFinally: true // Force execution after timeout }) // Specify target instance import { getCurrentInstance } from 'vue' const instance = getCurrentInstance() tryOnShow(() => { console.log('Registered on specific instance') }, instance) // Error handling try { await tryOnShow(() => { console.log('Attempting registration') }, undefined, { retry: 3, runFinally: false // Throw exception on failure }) } catch (error) { console.error('Registration failed:', error) } ``` -------------------------------- ### Initialize Component with tryOnInit Lifecycle Hook (TypeScript) Source: https://github.com/uni-helper/uni-use/blob/main/src/tryOnInit/index.md The tryOnInit function attempts to execute the provided callback, which represents the component's onInit logic. It supports retry attempts if the initial execution fails. After exhausting retries, it either executes a fallback function via `runFinally` or throws an error, ensuring robust initialization. ```typescript import { tryOnInit } from '@uni-helper/uni-use'; tryOnInit(() => { // Your component initialization logic here console.log('Component initialized successfully'); }); ``` -------------------------------- ### Async Storage Operation with useStorageAsync in TypeScript Source: https://github.com/uni-helper/uni-use/blob/main/src/useStorageAsync/index.md Demonstrates how to use the `useStorageAsync` hook to manage asynchronous storage. It shows initial assignment, updating the value, and reading the stored value. Note that the value is reactive but not immediately written to storage. ```typescript import { useStorageAsync } from '@uni-helper/uni-use'; const token = useStorageAsync('authorization', ''); // Assignment token.value = 'authorization-token'; // Reading console.log(token.value); // authorization-token ``` -------------------------------- ### Execute Callback on Component Ready with Retry Source: https://github.com/uni-helper/uni-use/blob/main/src/tryOnReady/index.md The tryOnReady function from '@uni-helper/uni-use' attempts to execute a provided callback function when the component is ready. It manages retry attempts and ensures the callback is eventually executed or an error is thrown. ```typescript import { tryOnReady } from '@uni-helper/uni-use'; tryOnReady(() => { // ... }); ``` -------------------------------- ### useRouter - Enhanced Routing Navigation Source: https://context7.com/uni-helper/uni-use/llms.txt Encapsulates uni-app routing APIs, providing Promise-based navigation, automatic TabBar detection, page stack management, and more. ```APIDOC ## useRouter - Enhanced Routing Navigation ### Description Encapsulates uni-app routing APIs, providing Promise-based navigation, automatic TabBar detection, page stack management, and more. ### Method Composition API function ### Endpoint N/A (Client-side function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { useRouter } from '@uni-helper/uni-use' // Initialize router - configure TabBar list const router = useRouter({ tryTabBar: true, // Automatically detect TabBar pages tabBarList: [ { pagePath: '/pages/index/index' }, { pagePath: '/pages/user/user' } ] }) // Navigate to page - automatically handle TabBar await router.navigate({ url: '/pages/detail/detail?id=123' }) // If it's a TabBar page, switchTab will be used automatically await router.navigate({ url: '/pages/index/index' }) // Redirect await router.redirect({ url: '/pages/login/login' }) // Go back to previous page await router.back({ delta: 1 }) // Relaunch application await router.reLaunch({ url: '/pages/index/index' }) // Access page stack information console.log('Current page:', router.current.value?.route) console.log('Previous page:', router.prev.value?.route) console.log('Current URL:', router.currentUrl.value) console.log('Page stack:', router.pages.value) // Watch for route changes watch(router.currentUrl, (url) => { console.log('Route changed to:', url) }) ``` ### Response #### Success Response (200) N/A (This is a composition function, not an API endpoint) #### Response Example N/A ``` -------------------------------- ### Update Service Provider Configuration with useProvider (TypeScript) Source: https://github.com/uni-helper/uni-use/blob/main/src/useProvider/index.md This snippet illustrates how to update the configuration of an existing service provider obtained via `useProvider`. It utilizes the spread operator to merge new configuration options with the existing ones, ensuring a complete and updated configuration is used. This method is useful for dynamically changing provider settings. ```typescript getProvider({ /* 新传入配置 */ }); ``` -------------------------------- ### tryOnReady - Safe onReady Lifecycle Hook with Retry Source: https://context7.com/uni-helper/uni-use/llms.txt Safely registers the `onReady` lifecycle hook with support for retries. This is useful for ensuring that code meant to run after the initial render is executed reliably. It takes a callback function and retry options. ```typescript import { tryOnReady } from '@uni-helper/uni-use' tryOnReady(() => { console.log('页面首次渲染完成') initChart() }) ``` -------------------------------- ### useUploadFile - File Upload Hook Source: https://context7.com/uni-helper/uni-use/llms.txt Provides a responsive file upload functionality with support for progress monitoring and upload abortion. It allows immediate or deferred execution of uploads, configuration of upload URLs and parameters, and provides reactive states for upload progress and completion status. ```typescript import { useUploadFile } from '@uni-helper/uni-use' // 基础上传 const { execute, data, progress, isUploading } = useUploadFile({ url: 'https://api.example.com/upload', immediate: false }) // 选择并上传文件 uni.chooseImage({ success: async (res) => { await execute({ filePath: res.tempFilePaths[0], name: 'file' }) console.log('上传结果:', data.value) } }) // 监听上传进度 watch(progress, (p) => { console.log(`上传进度: ${p}%`) }) // 中止上传 const { abort, isAborted } = useUploadFile({ url: '/upload', immediate: false }) execute({ filePath: '/tmp/large.zip', name: 'file' }) setTimeout(() => abort(), 3000) ```