Skip to content

useScreenOrientation

锁定或解锁屏幕方向,防止设备旋转时自动切换横竖屏。仅移动设备支持

前置依赖

依赖参数

参数名类型说明
deps.vue.ref<T>(value: T) => Ref<T>Vue ref 函数
deps.vue.onMounted(fn: () => void) => voidVue onMounted 钩子
deps.vue.onUnmounted(fn: () => void) => voidVue onUnmounted 钩子
deps.orientationScreenOrientationScreen Orientation 对象
deps.isMobileboolean是否为移动设备(使用 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'

参数

参数名类型必填说明
depsUseScreenOrientationDeps依赖注入对象

返回值

属性类型说明
isSupportedRef<boolean>是否支持屏幕方向 API
orientationRef<OrientationType>当前方向类型
angleRef<number>当前旋转角度
isLockedRef<boolean>是否已锁定
errorRef<string | null>错误信息
lock(orientation) => Promise<void>锁定屏幕方向
unlock() => void解锁屏幕方向

工作原理

  1. 检查是否为移动设备(桌面设备不支持)
  2. 监听屏幕方向变化事件
  3. 调用 lock() 锁定指定方向
  4. 调用 unlock() 解锁方向
  5. 组件卸载时自动解锁

方向类型说明:

  • portrait: 竖屏(任意竖屏方向)
  • landscape: 横屏(任意横屏方向)
  • portrait-primary: 主竖屏(通常是正向竖屏)
  • landscape-primary: 主横屏(通常是向左横屏)

注意:

  • 仅移动设备支持此功能
  • 桌面浏览器通常不支持屏幕方向锁定
  • 组件卸载时会自动解锁方向

适用场景:

  • 游戏(锁定横屏)
  • 视频播放(锁定横屏)
  • 阅读应用(锁定竖屏)

异常

无异常抛出