Vue 组件 v-full 监听浏览器进入退出全屏事件

发布时间 2023-11-02 01:06:18作者: 金科许俊

1、新建 full.ts

// 导出Full对象
export const Full = {
    // 挂载函数
    mounted(el: any, binding: any) {

        // 获取传入的函数
        const handler = binding.value
        // 设置事件监听的参数
        const options = {
            passive: !binding.modifiers?.active
        }

        // 定义一个函数,用于防抖
        function debounce(
            fn: { apply: (arg0: any, arg1: IArguments) => void },
            delay = 16
        ) {
            let t: any = null
            return function (this: unknown) {
                if (t) {
                    clearTimeout(t)
                }


                const context = this
                const args = arguments
                t = setTimeout(function () {
                    fn.apply(context, args)
                }, delay)
            }
        }




        // 监听resize事件,并传入handler和options
        window.addEventListener('resize', () => {

            var isFull = el._isFull || false


            if (window.innerHeight === screen.height && !isFull) {


                // 调用debounce函数,传入handler和options
                debounce(binding.value, Number(binding.arg) || 16)
                el._isFull = true; // 全屏
            } else if (isFull) {
                // 调用debounce函数,传入handler和options
                debounce(binding.value, Number(binding.arg) || 16)
                el._isFull = false; // 退出全屏
            }

        });


        // 将函数和options赋值给el._onFull
        el._onFull = {
            handler,
            options
        }

        // 如果不是quiet修饰符,则立即执行函数
        if (!binding.modifiers?.quiet) {
            handler()
        }
    },

    // 卸载函数
    unmounted(el: any) {
        // 如果el._onFull不存在,则直接返回
        if (!el._onFull) return

        // 获取el._onFull中的函数和options
        const { handler, options } = el._onFull
        // 从window中移除fullscreenchange事件,并传入handler和options
        window.removeEventListener('resize', handler, options)
        // 删除el._onFull
        delete el._onFull
        delete el._isFull
    }
}

// 导出Full对象
export default Full

2、main.ts 全局引入

import { Full } from '/@/store/modules/full'// 窗体全屏变化事件
 const app = createApp(App)
 app.directive('full', Full) //全局挂载窗体变化事件

3、组件使用

 <div  v-full:200="onResize"></div> // 200 指间隔200ms onResize 触发的事件