uni-use

repository·main·Indexed 41 days ago

https://github.com/uni-helper/uni-use

A collection of Vue 3 Composition API utilities specifically designed for uni-app development. It provides encapsulated functions for lifecycle hooks (e.g., tryOnLoad, tryOnBackPress), UI/UX utilities (useToast, useModal, useLoading), and system utilities (useNetwork, useStorage, useRoute). Version 0.19.17 requires Node >= 18 and is compatible with @vueuse/core@9.

Tokens
34.7K
Snippets
114
Records
138
Agent score
50%

What's inside uni-use

  1. Introduction to UniUse

    main
    UniUse is a composition utility toolkit specifically tailored for uni-app. It provides a rich set of encapsulated functions for common uni-app tasks, offering out-of-the-box support for the Vue 3 Composition API. All functions are designed with TypeScript in mind, providing full type inference without requiring manual type annotations.
  2. Explore @uni-helper/uni-use function list

    main

    The @uni-helper/uni-use package provides a collection of composable functions (hooks) designed for Uni-app development. The available functions are categorized into lifecycle hooks (prefixed with tryOn), UI/UX utilities (like useToast, useModal, useLoading), and system/environment utilities (like useNetwork, useStorage, useRoute).

    Available function categories:
    
    - **Lifecycle Hooks**: `tryOnBackPress`, `tryOnHide`, `tryOnInit`, `tryOnLoad`, `tryOnReady`, `tryOnScopeDispose`, `tryOnShow`, `tryOnUnload`
    - **UI/UX Utilities**: `useActionSheet`, `useClipboardData`, `useDownloadFile`, `useLoading`, `useModal`, `useScanCode`, `useToast`, `useUploadFile`
    - **System & Environment**: `useNetwork`, `useOnline`, `usePreferredDark`, `usePreferredLanguage`, `useScreenBrightness`, `useStorage`, `useStorageSync`
    - **Routing & Navigation**: `usePage`, `usePages`, `usePrevPage`, `usePrevRoute`, `useRoute`, `useRouter`, `usePageScroll`
    - **Data & State**: `useGlobalData`, `useInterceptor`, `useProvider`, `useQuery`, `useRequest`, `useSelectorQuery`, `useSocket`
  3. Environment Limitations

    main

    When running in mini-program or mobile app environments, be aware of the following constraints:

    • Missing Globals: Certain global variables like window or navigator are unavailable.
    • API Dependency: Functionality is limited to what the uni-app APIs can implement (e.g., interceptors, storage). If uni-app doesn't support a feature (like intercepting synchronous APIs or clipboard changes triggered externally), uni-use cannot support it either.
    • Top-level Await: Use of top-level await is not supported.

    Recommendation: For web-only development, use standard vue and vueuse directly to avoid environment-specific checks and to benefit from the full ecosystem.

  4. Understand environment limitations in Mini Programs and Mobile Apps

    main

    When developing for Mini Programs or mobile applications, be aware of the following constraints:

    • Missing Globals: Variables like window and navigator are unavailable.
    • API Dependency: Functionality is strictly limited to what the uni-app APIs provide (e.g., interceptors, storage). If uni-app does not support a feature (like intercepting synchronous APIs or listening to clipboard changes), @uni-helper/uni-use cannot support it either.
    • No Top-level Await: You cannot use top-level await in these environments.

    Recommendation: For web-only development, use standard vue instead of uni-app to avoid environment checks and to gain full support for the vueuse ecosystem.

  5. Configure Vite for @uni-helper/uni-use in Vite + Vue3 projects

    main

    When using @uni-helper/uni-use in a vite + vue3 project, you must set the build target to es6 because the library transpiles non-uni API parts to ES2017. Ensure the @dcloudio/vite-plugin-uni plugin is included in your plugins array.

    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(),
        // ...,
      ],
    });
  6. Use useRequest for network requests

    main

    The useRequest hook is a wrapper around uni.request designed to align with the API patterns of @vueuse/core (specifically v10.7.1). It provides a reactive way to handle network requests within a UniApp environment.

    For detailed implementation patterns and advanced usage, refer to the @vueuse/core useAxios documentation, as useRequest follows a similar mental model.

    Note: The return value includes a task object, which allows you to manually control the request (e.g., for aborting the request).

    // Note: Implementation details follow @vueuse/core useAxios patterns.
    // The return value includes a 'task' object for manual request control.
    const { data, error, loading, task } = useRequest(options);
  7. Use useSocket for uni-app socket communication

    main

    The useSocket hook provides a wrapper around uni-app socket APIs, following the same pattern and API design as @vueuse/core's useWebSocket. It allows you to manage WebSocket connections within a uni-app environment.

    Because this is a wrapper for uni-app, you should refer to the VueUse useWebSocket documentation for detailed usage patterns, options, and lifecycle management.

    Note: The return value includes a task object which can be used to perform manual socket operations.

    // Refer to VueUse documentation for specific implementation details:
    // https://vueuse.org/core/useWebSocket/
  8. Configure Vite for @uni-helper/uni-use

    main

    For vite + vue3 projects, you must set the build target to es6. Additionally, exclude vue-demi from optimizeDeps to ensure compatibility. The @uni-helper/uni-use library uses unbuild to transpile non-uni API parts to ES2017 (ES8), while uni APIs are handled by the official uni-app plugin.

    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(),
        // ...,
      ],
    });
  9. Pass and parse complex JSON data in URLs

    main

    To pass objects through page navigation, stringify the object and append it to the URL. useQuery will automatically detect and parse these JSON strings back into objects.

    Recommended Pattern: Use encodeURIComponent(JSON.stringify(data)) when navigating to ensure special characters are handled correctly.

    Example Navigation:

    const data = { id: 123, type: 'coal' };
    uni.navigateTo({
      url: '/pages/detail?resData=' + encodeURIComponent(JSON.stringify(data))
    });

    Example Retrieval:

    const { value: resData } = useQuery('resData');
    // resData.value = { id: 123, type: 'coal' }
    // Recommended way to navigate with objects
    const data = { id: 123, name: 'test', details: { amount: 50 } };
    uni.navigateTo({
      url: `/pages/detail?resData=${encodeURIComponent(JSON.stringify(data))}`
    });
  10. Use @uni-helper/uni-use

    main

    Import functions directly from @uni-helper/uni-use. For example, you can use tryOnLoad to safely execute logic during the onLoad lifecycle event in a uni-app environment.

    import { tryOnLoad } from '@uni-helper/uni-use';
    
    tryOnLoad(() => {
      console.log('onLoad');
    });
  11. Add Polyfills to your application

    main

    Since the library targets environments like mini-programs, you may need to manually add polyfills in your src/main.ts or src/main.js. You can use core-js or es-shims.

    Example using core-js:

    // You can add additional 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,
      };
    }
  12. Install @uni-helper/uni-use

    main

    Install @uni-helper/uni-use along with @vueuse/core@9. Note that node >= 18 is required.

    If you intend to use @vueuse/core v10 or higher, you must provide your own polyfills or use vite-plugin-uni-polyfill due to compatibility requirements with uni-app.

    Package Manager Specifics:

    • Yarn (v2+): Set nodeLinker to node_modules in your configuration.
    • pnpm: Set shamefully-hoist to true in your .npmrc.
    npm install @uni-helper/uni-use @vueuse/core@9