行业知识
封装一个页面自适应方法
2026-11-13 07:39:09
来源:互联网转载
封装一个页面自适应方法
在 Vue 中,你可以封装一个页面自适应的方法来根据屏幕大小动态调整页面的布局和样式。以下是一个示例代码:
export const getPageSize = () => { const { innerWidth, innerHeight } = window; const width = innerWidth > 1920 ? 1920 : innerWidth; const height = innerHeight > 1080 ? 1080 : innerHeight; const ratio = innerWidth / innerHeight; const isMobile = innerWidth = 768 && innerWidth = 1024; return { width, height, ratio, isMobile, isTablet, isDesktop, };}; 你可以将上述代码保存为一个单独的文件,例如 utils.js。然后在你的 Vue 组件中导入并使用该方法来获取页面的自适应信息。
import { getPageSize } from './utils';export default { mounted() { const pageSize = getPageSize(); console.log(pageSize); },}; 在上述示例中,getPageSize 方法返回一个对象,包含了页面的宽度、高度、宽高比、以及是否为移动端、平板端或桌面端的标识。你可以根据这些信息在组件中动态调整页面的布局和样式。
下一篇:U盘歌曲下载指南