配置前言
项目构建:基于vue-cli3构建(构建时注意让各插件可以有自己的json配置文件),使用mintUI进行组件开发,使用px2rem-loader和postcss-px2rem-exclude进行rem适配
实现原理:每次打包,webpack通过使用插件postcss-px2rem-exclude,帮我们自动将px单位转换成rem单位
第一步,使用vue-cli3构建基础项目,注意构建时让配置有各自专属文件,方便第六步配置postcss.config.js,具体可参考我之前写的博客:Vue CLI 3 使用步骤
第二步,安装mintUI,项目根目录下打开命令行工具,输入:
npm install mint-ui -S
第三步,安装px2rem-loader和postcss-px2rem-exclude两个插件
npm install px2rem-loader postcss-px2rem-exclude -S
第四步,在根目录src中新建util目录下新建rem.js等比适配文件
// rem等比适配配置文件
// 基准大小
const baseSize = 75
// 设置 rem 函数
function setRem () {
// 当前页面宽度相对于 375宽的缩放比例,可根据自己需要修改,一般设计稿都是宽750(图方便可以拿到设计图后改过来)。
const scale = document.documentElement.clientWidth / 375
// 设置页面根节点字体大小(“Math.min(scale, 2)” 指最高放大比例为2,可根据实际业务需求调整)
document.documentElement.style.fontSize = baseSize * Math.min(scale, 2) + 'px'
}
// 初始化
setRem()
// 改变窗口大小时重新设置 rem
window.onresize = function () {
setRem()
}
第五步,在main.js中引入适配文件
import './util/rem'
第六步,在根目录postcss.config.js下配置:
module.exports = {
plugins: {
'autoprefixer': {},
'postcss-px2rem-exclude': {
//这里注意与rem.js中的基准大小保持一致
'remUnit': 75,
'exclude': '/node_modules/i'
}
}
}
示例页面代码,直接使用px即可,webpack编译时会自动转成rem
覆盖根目录/src/App.vue
<template>
<div id="app">
<router-view />
</div>
</template>
<style >
#app {
width: 100%;
height: 100vh;
}
* {
margin: 0;
padding: 0;
}
</style>
覆盖根目录/src/views/Home.vue
<template>
<div class="home">
<div class="header">这是50px高的头部</div>
<div class="container">这是中间容器</div>
<div class="footer">这是50px高的底部</div>
</div>
</template>
<script>
export default {
}
</script>
<style scoped>
.home {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
font-size: 20px;
.header {
height: 50px;
background: yellow;
}
.container {
flex: 1;
background: cyan;
}
.footer {
height: 50px;
background: #ccc;
}
}
</style>
示例页面效果
啊,interesting ٩(๑>◡<๑)۶ 。
如果文章对您有所帮助,可以将网页收藏到浏览器收藏夹,方便以后用到来翻,当然我就是这么干的。然后,点赞,关注,谢谢。