一. 移动端适配方案:amfe-flexible和postcss-pxtorem插件结合
amfe-flexible:配置可伸缩布局方案,主要是将1rem设为viewWidth/10。根据设备宽度,修改根元素html的大小,以适配不一样终端。
postcss-pxtorem:是postcss的插件,用于将像素单元生成rem单位,它可以自动将px转换成rem,并且对一些特殊情况进行处理。
第一步:安装两个插件
npm i amfe-flexible --save-dev
npm i postcss-pxtorem --save-dev
第二步:在main.js文件中导入amfe-flexible
import 'amfe-flexible'
第三步:vue.config.js中配置postcss-pxtorem
const {
defineConfig } = require("@vue/cli-service");
module.exports = defineConfig({
lintOnSave: false,
transpileDependencies: true,
// 配置css前缀,px转rem
css: {
loaderOptions: {
postcss: {
postcssOptions:{
plugins: [
//autoprefixer(),
require("postcss-pxtorem")({
rootValue: 256,
// rootValue根据设计稿宽度除以10进行设置,这边假设设计稿为2560,即rootValue设为256
propList: ["*"]
})
]
}
}
}
},
});
复制这一块代码到你的vue.config.js
也可以在postcss.config.js配置,没有就在项目根目录下创建
module.exports = {
"plugins": {
'postcss-pxtorem': {
rootValue: 192,
propList: ['*']
}
}
}
// rootValue根据设计稿宽度除以10进行设置,这边假设设计稿为1920,即rootValue设为192
二. 可视化大屏适配解 : 主打css3中transform的缩放属性scale
1. 大屏适配的基本要求要满足一下3点
1,横向、纵向不能出现滚动条
2,可全屏(就是F11全屏模式)
3,不论在多大的屏幕中显示,页面不可变形,最好是肉眼看不出任何问题
2.解决方案
1.css3的scale进行适配。原理:就是我们假设按照1920×1080的设计图正常使用px单位去写页面,然后当页面变化时,使用scale动态的放大或者缩小
2.rem适配,利用amfe-flexible和postcss-pxtorem插件结合
3.flex适配结合百分比适配
3.封装组件
我的想法是封装一个vue组件,利用插槽属性,把需要可视化适配的页面包裹在该组件里面达到了复用的效果。
<template>
<div class="scaleBox" :style="styleObj">
<slot></slot>
</div>
</template>
<script>
export default {
name: "ScaleBox",
data(){
return{
scaleX:1,
scaleY:1,
}
},
computed:{
styleObj(){
return {
transform: `scale(${
this.scaleX}, ${
this.scaleY}) translate(-50%,-50%)`
//铺满但是会变形
//transform: `scale(${this.scale}) translate(-50%,0)`
//不变形会有留白
}
}
},
methods:{
getScale(){
const ww = window.innerWidth / 1920 //window.screen.width
const wh = window.innerHeight / 1080 //window.screen.height
this.scale = ww < wh ? ww: wh
this.scaleX = ww
this.scaleY = wh
},
resizeHanlder(){
this.getScale()
}
},
mounted() {
this.getScale()
window.addEventListener('resize', this.resizeHanlder);
},
beforeDestroy() {
window.removeEventListener('resize', this.resizeHanlder)
}
};
</script>
<style lang="less" scoped>
.scaleBox{
width: 1920px; /* 设计稿宽度 */
height: 1080px; /* 设计稿高度 */
position: absolute;
top: 50%;
/* top:0; */
left: 50%;
transform: translate(-50%, -50%);
transform-origin: left top;
overflow: hidden;
}
</style>
scale设置两个值scaleX,scaleY,宽高铺满但会变形
scale设置一个值,不变形但是会留白