跪拜 Guibai
← Back to the summary

uView Pro X's 8 Composables Kill the Most Repetitive uni-app x Page Work

When people think of UI component libraries, they usually think of visible things like buttons, forms, and popups. But when writing mobile pages with uni-app x, the real time sink is another layer: how tall the window is, how much to reserve for the status bar, whether the bottom gesture bar blocks buttons, whether a half-swipe counts as horizontal or vertical, and how many seconds a countdown loses when the app goes to the background. These might need to be rewritten for every project, and on top of that you also have to consider multi-platform compatibility.

uView Pro X, besides its rich component set, also includes a group of page-level composables. They share the same implementation and entry point as the components, so the values the page gets are the same set used internally by the components.

image.png

Below we pick 8 of the most commonly used capabilities to help us reuse them quickly when writing pages.

1. Overview of the 8 composables

Composable Purpose One-line usage
useWindowInfo Window size, status bar height, safe area raw data const { statusBarHeight, windowWidth } = useWindowInfo()
useSafeArea Top/bottom safe area inset distances const { top, bottom } = useSafeArea()
useRect Measure element size and position const { getRect } = useRect()
useTouch Touch/mouse gesture state and direction detection const touch = useTouch()
useCountDown Countdown, with pause and reset const { current, start } = useCountDown({ time: 60000 })
useDebounce Debounce, delay can be temporarily specified const { debounce } = useDebounce(500)
useThrottle Throttle, leading-edge executes immediately const { throttle } = useThrottle(500)
useDeviceInfo Device model, platform, OS version const { platform, deviceModel } = useDeviceInfo()

All import from the library entry, no extra package installation needed:

import { useWindowInfo, useSafeArea, useRect, useTouch } from '@/uni_modules/uview-pro-x'

Even if you don't use any ux-* components, these composables can be used standalone in existing projects.

2. useWindowInfo: window data shared across the whole page, accurate on the first frame

const { info, windowWidth, windowHeight, statusBarHeight, safeArea, safeAreaInsets } = useWindowInfo()

Returned fields directly correspond to the common items of uni.getWindowInfo(): pixelRatio, screenWidth/Height, windowWidth/Height, statusBarHeight, windowTop/windowBottom, screenTop, safeArea, safeAreaInsets. You can grab the whole info object or destructure individual fields, and the destructured ones are all computed.

image.png

Refresh timing and sharing

The intuitive approach is to call uni.getWindowInfo() in setup, but on the App side the layout isn't stable at that point, so you get the startup dimensions and the page may "collapse then settle back". This composable refreshes twice:

// Module-level singleton: all callers share the same data source
const windowInfo = ref<WindowInfo>(gatherWindowInfo())

export function useWindowInfo(): WindowInfoReturn {
    refreshWindowInfo()
    onMounted(() => {
        // Refresh again after mount, waiting for App layout to stabilize
        setTimeout(() => {
            refreshWindowInfo()
        }, 0)
    })
    // ...
}

First refresh ensures rendering during setup, the second ensures accurate first-screen dimensions.

The data source is module-level. Ten places in a page calling useWindowInfo() all read the same ref, so there's no case of "two heights on the same page". The page and components get the same value, so the basis is naturally consistent.

Fields like statusBarHeight and screenTop may be missing on some platforms; the composable defaults them to 0, so the page doesn't have to write ?? everywhere.

Edge case: null and rotation

safeArea / safeAreaInsets keep the null semantics (some platforms simply don't have them), so check for null before reading:

const insets = info.value.safeAreaInsets
const bottom = insets != null ? insets.bottom : 0

Also, it doesn't listen to resize or rotation; it updates only after you re-enter the page when switching between portrait and landscape. For real-time response to orientation changes, typically use width-height comparison (windowWidth > windowHeight).

3. useSafeArea: get safe area separately, don't mix with the status bar

const { top, bottom } = useSafeArea()

It only returns two values, both computed, and both are 0 when there is no safe area. uView Pro X's internal components also use it: ux-tabbar and ux-safe-bottom get the bottom safe area, and ux-popup reserves bottom space for overlays, all through this same call:

// Inside ux-tabbar
const { bottom: safeBottom } = useSafeArea()

Pages writing sticky bottom buttons, floating balls, or full-screen overlays use the same call.

image.png

Why split it out separately

This composable exists to separate two concepts that are easy to confuse:

Name What it is Where to use
statusBarHeight System status bar height (the time/signal bar) Top offset for custom navigation bars
safeAreaInsets.top / bottom Safe area inset distances (cuts, rounded corners, bottom gesture bar margin) Extra padding so content isn't obscured

On portrait phones these two are often close, so using the safe area top as the status bar height seems fine on most models. But in iOS landscape statusBarHeight is 0 while the safe area inset remains, causing misalignment.

So the API separates these semantics: useSafeArea expresses only "safe area inset distances", without mixing in the status bar; for the status bar, go through useWindowInfo.

When writing a page, you don't need to check the device model or remember the relationship between these two numbers.

Edge case: 0 is also a valid value

4. useRect: measure element size and position in one line

const { getRect } = useRect()

const box = ref<UniElement | null>(null)

async function measure(): Promise<void> {
    const rect = await getRect(box.value)
    if (rect == null) return
    console.log(rect.width, rect.height, rect.top, rect.left)
}

onMounted((): void => {
    measure()
})
image.png

Compared with createSelectorQuery

The old approach was uni.createSelectorQuery().select(...).boundingClientRect(), which gave a set of fields in a callback and required handling "element not found". This composable directly calls the element's getBoundingClientRectAsync(), returning a standard DOMRect with width / height / top / left / right / bottom, consistent across Web, App, HarmonyOS, and WeChat mini-programs.

If the ref isn't bound yet or the element is conditionally rendered away, it returns null, so you don't have to distinguish "query failed" from "element doesn't exist".

Edge case: call after render

5. useTouch: gesture state and direction detection, one set of code across three platforms

const touch = useTouch()
<view
    @touchstart="touch.start"
    @touchmove="touch.move"
    @touchend="touch.end"
/>

This returns a set of reactive states covering most gesture interactions:

Field Meaning
startX / startY Starting point coordinates
deltaX / deltaY Displacement from start (signed)
offsetX / offsetY Absolute displacement
direction '' / 'vertical' / 'horizontal'
isTap Whether it still counts as a tap
skipMove Whether to stop consuming horizontal movement
dragging Whether a drag is in progress

How the three platforms' events are normalized

H5 has mouse events (UniMouseEvent), while App has only touch events (UniTouchEvent). Writing for only one means the other side gets "no response". The composable internally uses conditional compilation to declare signatures separately, then normalizes them into clientX / clientY:

// #ifndef APP
const start = (e: UniTouchEvent | UniMouseEvent): void => {
    const touches = getClientXY(e)
// #endif

// #ifdef APP
const start = (e: UniTouchEvent): void => {
    const touches = e.touches[0]
// #endif

The page doesn't need any platform checks. For H5 and mini-programs that want extra mouse drag support, add a mouse binding (wrapped in #ifndef APP so it won't compile on App).

When sliding diagonally, both horizontal and vertical displacement grow, so the direction can jump back and forth and floating layers jitter. The approach here is "first come, first locked":

const MIN_DISTANCE = 10           // Minimum displacement for a valid swipe
const LOCK_DIRECTION_DISTANCE = 10 // Only allow re-determination when both axes are below this
const TAP_OFFSET = 5              // Beyond this, no longer counts as a tap
// After locking direction, only allow re-determination if both axes are small
if (direction.value == '' ||
    (offsetX.value < LOCK_DIRECTION_DISTANCE && offsetY.value < LOCK_DIRECTION_DISTANCE)) {
    direction.value = getSlideDirection(offsetX.value, offsetY.value)
}

// A finger twitch shouldn't count as a tap
if (isTap.value && (offsetX.value > TAP_OFFSET || offsetY.value > TAP_OFFSET)) {
    isTap.value = false
}

// Once judged as vertical, horizontal movement is no longer consumed
if (direction.value == 'vertical') {
    skipMove.value = true
}

skipMove is there for when scrolling and dragging compete for the gesture: once the direction is judged vertical, stop consuming horizontal movement so you don't "try to scroll the page but end up dragging a floating layer halfway".

A complete pull-to-close detection is just a few lines:

function onTouchEnd(): void {
    touch.end()
    if (touch.direction.value == 'vertical' && touch.deltaY.value > 80) {
        closePopup()
    }
}

Edge case: event binding and duplicate triggers

6. useCountDown: no need to maintain timers yourself

const { current, start, pause, reset } = useCountDown({
    time: 60 * 1000,
    onChange: (t) => { console.log(t.seconds) },
    onFinish: () => { console.log('finished') }
})

start()

current is a computed property that directly provides days / hours / minutes / seconds / milliseconds / remainTime. reset() without arguments returns to the initial value; with arguments, it restarts with a new duration. pause() stops at any time.

image.png

Why not use remain--

Writing remain-- yourself has a drift problem: setInterval isn't guaranteed to be on time, and App backgrounding or inactive H5 tabs get throttled or even paused, so when the user returns, the number has lost seconds. This composable records endTime and recalculates on each tick:

endTime.value = Date.now() + remainTime.value
const getRemainTime = (): number => Math.max(endTime.value - Date.now(), 0)

A late timer only affects the refresh frequency, not the remaining time.

There's also a small optimization in second-level mode: if the second hasn't changed, don't write to reactive state, saving unnecessary re-renders:

if (!isSameSecond(remain, remainTime.value) || remain == 0) {
    setRemainTime(remain)
}

onUnmounted automatically clears the timer, so no callbacks hit a destroyed component after the page exits.

Edge case: time and reset

7. useDebounce / useThrottle: input debounce and click throttle

const { debounce } = useDebounce(500)

function onInput(val: string): void {
    keyword.value = val
    debounce(() => { doSearch() })          // Use default 500ms
    debounce(() => { doSearch() }, 200)     // Temporarily change to 200ms
}
const { throttle } = useThrottle(500)

// Scroll, drag, button double-click prevention
function onScroll(): void {
    throttle(() => { syncPosition() })
}

What if the delay changes

If a new debounce instance is created every call, the previous timer is never cleared, leading to "sometimes fires, sometimes doesn't", especially when the delay changes. Here, a factory is cached by delay. If the delay is unchanged, the instance is reused (timer state is preserved); if it changes, the instance is rebuilt, and a generation marker invalidates any un-fired callbacks from the old instance:

let generation = 0

const makeRun = (wait: number): (() => void) => {
    const myGen = ++generation
    return debounce(() => {
        // If the generation is stale, the factory was rebuilt, so old callbacks don't run
        if (myGen === generation && currentCallback != null) {
            currentCallback()
        }
    }, wait)
}

useThrottle uses the same structure; underneath it's leading-edge (executes immediately on first call), suitable for scroll, drag, and button double-click prevention.

Edge case: don't put it in templates

The call must be inside a function body, not as a template expression:

<!-- Not recommended: creates a new instance on every render -->
<ux-input @input="debounce(search, 300)" />

8. useDeviceInfo: model, platform, OS version in one line

const { platform, deviceBrand, deviceModel, osName, osVersion } = useDeviceInfo()

Fields directly correspond to uni.getDeviceInfo(): deviceBrand, deviceModel, deviceType, deviceOrientation, platform, osName, osVersion, system.

image.png

Collection timing

Device information doesn't change during runtime, so collecting once at module load is enough; window information depends on layout, so it needs a refresh after mount. Both are module-level shared, but with different refresh strategies:

Collection timing Refresh after mount
useDeviceInfo Once at module load Not needed
useWindowInfo Module load + delayed once after mount Needed

uni.getSystemInfoSync has been split into getDeviceInfo / getAppBaseInfo / getWindowInfo; the device dimension is now consolidated under getDeviceInfo, and the page side doesn't need to care which interface it maps to. ux-top-tips uses useWindowInfo + useDeviceInfo together when determining top offsets.

Edge case: snapshot fields

deviceOrientation is a snapshot at collection time. To respond to rotation, judge by window dimensions (windowWidth > windowHeight), not this field.

9. Summary

Each composable alone is not complex, and you could write it yourself. The problem is that every page would need to rewrite it: one missed null check, one forgotten timer clear, one skipped post-mount refresh, and another occasional bug appears in production.

By putting them in the library, pages and components use the same set of values. ux-tabbar and ux-safe-bottom get the bottom safe area with useSafeArea(), ux-popup uses both useSafeArea() and useWindowInfo(), ux-top-tips uses useWindowInfo() plus useDeviceInfo(), and ux-sticky, ux-waterfall, and ux-button measure sizes with useRect(). The case where your own calculated safe area doesn't match what the component built in won't happen again.

Platform differences are also maintained once: touch vs. mouse event differences, conditional compilation branches, null fallbacks, and timing issues are all in the library, and they get fixed with version upgrades instead of being re-stumbled upon on every page.

There's no third-party runtime library; composables and components are exported from the same entry. Install the component library and you have them all, but you can also take just the composables without using components.

10. How to use

Search uView Pro X on the DCloud plugin market, import it into a uni-app x project, and files land in uni_modules/uview-pro-x/. Plugin URL: https://ext.dcloud.net.cn/plugin?id=30343

Import named from the library entry and use:

import { 
    useWindowInfo, 
    useSafeArea, 
    useRect, 
    useTouch, 
    useCountDown 
} from '@/uni_modules/uview-pro-x'