用vue开发一个h5移动端项目需要做适配
传统方法
在public文件夹下html页面加入js,css中样式用到px的地方改为rem(真实宽高/一个固定比例)
<!--适配-->
<script type="text/javascript">
var html = document.querySelector('html');
changeRem();
window.addEventListener('resize', changeRem);
function changeRem() {
var width = html.getBoundingClientRect().width;
html.style.fontSize = width / 19.2 + 'px';
console.log(html.style.fontSize)
}
</script>
解决方案
1.第一步:安装三个插件
npm install amfe-flexible -D
npm install postcss-pxtorem -D
npm install autoprefixer -D
2.第二步:在main.js文件中导入amfe-flexible
import 'amfe-flexible'
第三步:vue.config.js中配置
const { defineConfig } = require("@vue/cli-service");
const autoprefixer = require("autoprefixer");
const pxtorem = require("postcss-pxtorem");
module.exports = defineConfig({
// 配置css前缀,px转rem
css: {
loaderOptions: {
postcss: {
postcssOptions:{
plugins: [
autoprefixer(),
pxtorem({
rootValue: 192, //根据设计稿宽度/10
propList: ["*"]
})
]
}
}
}
}
});
第四步:页面使用
在css中可以直接写px,会被转化为rem,不用去计算rem值,从而做到自适应伸缩。