前言
当我们使用Ant Design Vue做后台开发的时候,我们可以直接用框架默认的尺寸不再响应式调整,这样在大屏上会看到更多信息。
有这么个说法我感觉还挺有道理的:
后台框架之所以不用rem做单位是因为后台对不同屏幕尺寸比例的一致性没有太大的要求,主要目的是查看数据,更大的尺寸能看到更多的数据。
如果我们确实要保证一定范围内比例都一致我们可以使用REM做页面适配。
但是Ant Design Vue是用PX做单位的,一些插件比如postcss-pxtorem也对他不生效。
其实Ant Design Vue内部是有比较简单的适配方法的。
https://www.antdv.com/docs/vue/customize-theme-cn
本文使用的版本是
1
| "ant-design-vue": "4.2.6",
|
REM页面适配
这里根字体大小设置为10,方便我们计算。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| <style> html { font-size: 10px; }
body { font-size: 1.4rem; color: #666666; } </style> <script> function debounce(fn, wait) { let timeout = null return function() { if (timeout !== null) clearTimeout(timeout) timeout = setTimeout(fn, wait) } }
function resize() { let designWidth = 1440; const mHtml = document.documentElement let width = mHtml.clientWidth
if (width < 1280) { width = 1280 }
if (width > 2560) { width = 2560 } mHtml.style.fontSize = 10.0 * (width / designWidth) + 'px' }
resize() window.addEventListener('resize', debounce(resize, 100)) </script>
|
Ant Design适配
Ant Design的所有组件的大小和字体会根据fontSize自动适应。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| <template> <a-config-provider :locale="zhCN" :theme="{ token: { colorPrimary: '#165DFF', fontSize: antFontSize } }" > <RouterView /> </a-config-provider> </template>
<script setup lang="ts"> import { RouterView } from 'vue-router' import zhCN from 'ant-design-vue/es/locale/zh_CN' import dayjs from 'dayjs' import 'dayjs/locale/zh-cn' import { ref } from 'vue'
dayjs.locale('cn')
let antFontSize = ref(14)
function resize() { const mHtml = document.documentElement let baseFontSize = mHtml.style.fontSize let baseFontSizeNum = Number(baseFontSize.replace('px', '')) antFontSize.value = baseFontSizeNum * 1.4 }
resize()
function debounce(fn: Function, wait: number) { let timeout: any = null return function() { if (timeout !== null) clearTimeout(timeout) timeout = setTimeout(fn, wait) } }
window.addEventListener('resize', debounce(resize, 100)) </script>
|
默认框架基准的字体大小是14,我们的基准是10,所以适配的时候根字体大小*1.4就行了。
postcss-pxtorem
如果我们的是新项目直接自己的都用rem就行,不用安装该插件。
如果是老项目,单位都用的px,我们可以安装插件帮我们转换。
安装
1
| npm install postcss-pxtorem --save
|
项目根目录添加postcss.config.cjs,会自动生效
1 2 3 4 5 6 7 8 9 10 11 12 13
| module.exports = { plugins: { 'postcss-pxtorem': { rootValue: 10, propList: ['*'], unitPrecision: 5, selectorBlackList: [], replace: true, mediaQuery: false, minPixelValue: 0 } } }
|
卸载插件
1
| npm uninstall postcss-pxtorem
|