封裝一個頁面自適應方法
在 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;const isTablet = innerWidth >= 768 && innerWidth < 1024;const isDesktop = 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 方法返回一個對象,包含了頁面的寬度、高度、寬高比、以及是否為移動端、平板端或桌面端的標識。你可以根據這些信息在組件中動態調整頁面的布局和樣式。