返回
一招搞定,轻松实现vue-cli3.0 px转rem,布局自适应不再难!
前端
2023-09-20 23:38:23
在移动端开发中,为了实现布局自适应,通常会使用rem单位。rem单位相对于根节点的字体大小,因此可以通过设置根节点的字体大小来控制整个页面的布局。
一、安装postcss-pxtorem插件
npm install postcss-pxtorem --save-dev
二、在postcss.config.js文件中添加配置
module.exports = {
plugins: {
'postcss-pxtorem': {
rootValue: 37.5, // 设计稿的根字体大小
unitPrecision: 5, // rem单位的小数点位数
propList: ['*'], // 需要转换的属性列表,*表示所有属性
selectorBlackList: [], // 不需要转换的选择器列表
}
}
};
三、在App.vue文件中设置viewport和meta标签
<template>
<div id="app">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<router-view />
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
remFontSize: 100
}
},
computed: {
htmlFontSize() {
return parseInt(window.innerWidth / 10)
}
},
mounted() {
this.remFontSize = this.htmlFontSize
window.addEventListener('resize', () => {
this.remFontSize = this.htmlFontSize
})
}
}
</script>
<style>
html {
font-size: {{ remFontSize }}px !important;
}
</style>
这样就完成了vue-cli3.0中px转rem的配置,你可以在开发中使用rem单位进行布局,页面会根据不同屏幕尺寸自动调整布局。