vue-use 中的 useFullscreen

2,065 阅读1分钟

vue-use中的useFullscreen

用法

import { useFullscreen } from '@vueuse/core'

const { isFullscreen, enter, exit, toggle } = useFullscreen()
// el 是组建实例 或者是一个 html 元素
const el = ref<HTMLElement | null>(null)

const { isFullscreen, enter, exit, toggle } = useFullscreen(el)

主要使用了Fullscreen_API

原理

  1. 定义functionsMap 是关于各个浏览器关于 fullScreen api的差异
  2. 定义函数 useFullscreen 参数有 target (也就是用户传递进来的) 和 option (在文档上并没有说明,猜测是内部使用)
  3. 定义内部变量
const { document = defaultDocument, autoExit = false } = options
// 做了一层容错处理对传递进来的 target
const targetRef = target || document?.querySelector('html')
const isFullscreen = ref(false)
//
functionsMap = [
    [
    'requestFullscreen', // 进入 fullScreen
    'exitFullscreen',  // 退出
    'fullscreenElement', // 执行的元素
    'fullscreenEnabled', //是一个 可读的 布尔值,表明是否可用 requestFullscreen
    'fullscreenchange', // 状态变化
    'fullscreenerror', // 发生错误
    ],
    ... // 其他的不过多 赘述
]
// 默认 使用第一个
let map: FunctionMap = functionsMap[0]
// 解构 有用的属性,像 enabled不再使用;EVENT表示的是一个 change 事件
const [REQUEST, EXIT, ELEMENT,, EVENT] = map

源码中一共暴露了 4个值,一个 isFullScreen,和 3个方法enter, exit, toggle

  1. exit 方法
    async function exit() {
    // 这个 element 也就是 fullscreenElement
    // EXIT 是 exitFullscreen(返回一个 Promise,可以使用await)
    if (document?.[ELEMENT])
    // isFullscreen 值为false
          await document[EXIT]()
        isFullscreen.value = false
    }
  1. enter 方法
async enter (){
// 先 执行退出
 await exit()
//元素进行解包
    const target = unrefElement(targetRef) as HTMLElement
    if (target) {
    // 也就是 requestFullscreen
      await target[REQUEST]()
      // 变换当前的值
      isFullscreen.value = true
    }
}
  1. toggle
async function toggle() {
    if (isFullscreen.value)
      await exit()
    else
      await enter()
  }
  1. 监听 change 事件(不一定用的是 vueuse 的方法变化,但是 isFullScreen要及时发生变化,所以要监听)
// event 也就是 change 事件,判断是否存在 全屏元素
if (document) {
    useEventListener(document, EVENT, () => {
      isFullscreen.value = !!document?.[ELEMENT]
    }, false)
  }

note: 暴露一些 ts 类型

微信截图_20220504184053.png