vue实现大屏自适应看这里!!cv就能用!!

6,385 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第1天,点击查看活动详情

小万来分享 (自己摸索的,不专业的话不要喷😅) 第一次接触大屏,领导给任务,让适配大小屏幕,然后我就面向百度了hhhh,看了很多版本都不太一样,于是我自己总结了一份,奶妈式教程,手把手教学,直接cv就可以用,这个方法也可以用来做移动端适配,只需要把 postcss.config.js文件里的大小改成移动端的设计稿大小/10,移动端俺没有实践过,小伙伴们需要的话可以试试哦,不出意外的话是没问题的吼吼

大屏

第一步:先下包,这里用到lib-flexible和postcss-pxtorem

直接下载postcss-pxtorem的话会报错,所以这里我们下载指定版本postcss-pxtorem@5.1.1

npm下载 npm install lib-flexible --save-dev

postcss-pxtorem:自动把px转成rem

npm install postcss-pxtorem@5.1.1 --save-dev

yarn 下载 yarn add lib-flexible

yarn add postcss-pxtorem@5.1.1

第二步:在main.js引入

import 'lib-flexible'

第三步:修改lib-flexible源文件配置

修改node_modules里lib-flexible里flexible.js,找到refreshRem 函数修改:

function refreshRem(){
        var width = docEl.getBoundingClientRect().width;
        if (width / dpr < 540) {
            width = 540 * dpr;
        }else if(width / dpr > 1980){
            width = 1980 * dpr
        }
        var rem = width / 10;
        docEl.style.fontSize = rem + 'px';
        flexible.rem = win.rem = rem;
    }

注意:这里只需要修改屏幕最大宽度和最小宽度即可(540和1980)

第四步:在vue.config.js里配置

module.exports = {
css: {
    sourceMap: false,
    loaderOptions: {
      css: {
        // options here will be passed to css-loader
      },
      postcss: {
        // options here will be passed to postcss-loader
      },
    },
  },
 }

第五步:在vue.config.js同级新建postcss.config.js

module.exports = {
  plugins: {
    'postcss-pxtorem': {
      rootValue: 192,
      propList: ['*'],
    },
  },
}

注意:这里的rootValue可以根据设计稿的大小/10即可

最后重新 npm run dev 或 yarn dev就ok啦

但是要注意,如果删除了node_modules的依赖,重新下载之后还是需要重新修改配置文件

第一天打卡成功,坚持分享!收到over~ 明天见😊