import { App } from 'vue' export default { // 注意点: 如果要将一个组件封装成一个插件, 那么必须提供一个install方法 // 那么必须在install方法中注册当前的这个组件 install(app: App) { /** * 获取屏幕宽高 兼容性处理 * return {width: 100, height: 100} */ app.config.globalProperties.$getScreen = (): { width: number height: number } => { let width let height if (window.innerWidth || window.innerHeight) { width = window.innerWidth height = window.innerHeight } else if (document.compatMode === 'BackCompat') { width = document.body.clientWidth height = document.body.clientHeight } else { width = document.documentElement.clientWidth height = document.documentElement.clientHeight } return { width, height } } /** * 获取元素样式 兼容性处理 * @param dom 元素 * @param name 属性 * return 500px */ app.config.globalProperties.$getStyleAttr = ( dom: any, name: any ): string => { if (dom.currentStyle) { return dom.currentStyle[name] } else { return getComputedStyle(dom)[name] } } /** * 获取页面滚动坐标值 兼容性处理 * return {x: 100, y: 100} */ app.config.globalProperties.$getPageScroll = (): { x: number y: number } => { let x let y if (window.pageXOffset || window.pageYOffset) { x = window.pageXOffset y = window.pageYOffset } else if (document.compatMode === 'BackCompat') { x = document.body.scrollLeft y = document.body.scrollTop } else { x = document.documentElement.scrollLeft y = document.documentElement.scrollTop } return { x, y } } // 函数防抖 - 输入框 app.config.globalProperties.$debounce = function ( fn: any, delay: number ): any { // fn = test let timerId: number | null | undefined = null return (...args: any) => { timerId && clearTimeout(timerId) timerId = window.setTimeout(() => { fn.apply(this, args) }, delay || 1000) } } // 函数节流 - onscroll/onresize app.config.globalProperties.$throttle = function ( fn: any, delay: number ): any { // fn = test let timerId: number | null | undefined = null let flag = true return (...args: any) => { if (!flag) { return } flag = false timerId && clearTimeout(timerId) timerId = window.setTimeout(() => { flag = true fn.apply(this, args) }, delay || 1000) } } } }