useScreenOrientation
锁定或解锁屏幕方向,防止设备旋转时自动切换横竖屏。仅移动设备支持
前置依赖
依赖参数
| 参数名 | 类型 | 说明 |
|---|---|---|
deps.vue.ref | <T>(value: T) => Ref<T> | Vue ref 函数 |
deps.vue.onMounted | (fn: () => void) => void | Vue onMounted 钩子 |
deps.vue.onUnmounted | (fn: () => void) => void | Vue onUnmounted 钩子 |
deps.orientation | ScreenOrientation | Screen Orientation 对象 |
deps.isMobile | boolean | 是否为移动设备(使用 isMobile() 函数检测) |
环境要求
浏览器 API: Screen Orientation API
平台支持:
- ✅ 移动端(Android Chrome、iOS Safari)
- ❌ 桌面端 - 不支持
函数签名
typescript
function useScreenOrientation(
deps: UseScreenOrientationDeps
): UseScreenOrientationReturn
interface UseScreenOrientationDeps {
vue: VueCompositionAPI
orientation: ScreenOrientation | undefined
isMobile: boolean
}
interface UseScreenOrientationReturn {
isSupported: Ref<boolean>
orientation: Ref<OrientationType>
angle: Ref<number>
isLocked: Ref<boolean>
error: Ref<string | null>
lock: (orientation: OrientationLockType) => Promise<void>
unlock: () => void
}
type OrientationType =
| 'portrait-primary'
| 'portrait-secondary'
| 'landscape-primary'
| 'landscape-secondary'
type OrientationLockType =
| 'any'
| 'natural'
| 'landscape'
| 'portrait'
| 'portrait-primary'
| 'portrait-secondary'
| 'landscape-primary'
| 'landscape-secondary'参数
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
deps | UseScreenOrientationDeps | 是 | 依赖注入对象 |
返回值
| 属性 | 类型 | 说明 |
|---|---|---|
isSupported | Ref<boolean> | 是否支持屏幕方向 API |
orientation | Ref<OrientationType> | 当前方向类型 |
angle | Ref<number> | 当前旋转角度 |
isLocked | Ref<boolean> | 是否已锁定 |
error | Ref<string | null> | 错误信息 |
lock | (orientation) => Promise<void> | 锁定屏幕方向 |
unlock | () => void | 解锁屏幕方向 |
工作原理
- 检查是否为移动设备(桌面设备不支持)
- 监听屏幕方向变化事件
- 调用
lock()锁定指定方向 - 调用
unlock()解锁方向 - 组件卸载时自动解锁
方向类型说明:
portrait: 竖屏(任意竖屏方向)landscape: 横屏(任意横屏方向)portrait-primary: 主竖屏(通常是正向竖屏)landscape-primary: 主横屏(通常是向左横屏)
注意:
- 仅移动设备支持此功能
- 桌面浏览器通常不支持屏幕方向锁定
- 组件卸载时会自动解锁方向
适用场景:
- 游戏(锁定横屏)
- 视频播放(锁定横屏)
- 阅读应用(锁定竖屏)
异常
无异常抛出