vue-cli3中PC端大屏自适应

232 阅读1分钟

前期准备

  • vue 2.0
  • vue-cli3 脚手架
  • flexible 插件 自适应插件
  • px2rem-loader 插件 将px转化为rem
  • postcss-loader postcss

第一步:安装插件

  1. npm i lib-flexible -S
  2. npm i px2rem-loader -D
  3. npm install --save-dev postcss-loader postcss

第二步:装好之后在main.js 里引入 lib-flexible

import 'lib-flexible

image.png

第三步: 在vue.config.js 中添加配置

module.exports = {
  chainWebpack: config => {
    config.module
      .rule("css")
      .test(/\.css$/)
      .oneOf("vue")
      .resourceQuery(/\?vue/)
      .use("px2rem")
      .loader("px2rem-loader")
      .options({
        remUnit: 192
      });
  }
}

第四步:设置flexible.js的宽度根据屏幕大小自动适配, 修改flexible.js 文件,(全局搜索 flexible.js)

image.png

修改后代码:

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

第五步:设置完成后重新启动项目,查看效果

测试代码

<template>
  <div class="bg">
    <div class="header">
      大屏展示
    </div>
    <div class="body">
        <div class="box-full">
          占满全行
        </div>
        <div class="box-half">
          占行一半
        </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "test",
  data() {
    return {
      name: `test`
    }
  },
  mounted() {
  },
  methods: {}
}
</script>

<style scoped>
  .bg{
    height: 100vh;
    width: 100vw;
    background: #efefef;
    /*overflow: hidden;*/
  }
  .header{
    height: 150px;
    text-align: center;
    font-size: 50px;
    line-height: 150px;
  }
  .body{
    height: calc(100% - 150px);
  }
  .body div{
    line-height: 150px;
    text-align: center;
    color: #fff;
    font-weight: bold;
  }
  .box-full {
    width: 1920px;
    height: 150px;
    background: red;
  }
  .box-half{
    width: 920px;
    height: 150px;
    background: green;
  }
</style>


20201010163534430.gif

只有启程,才会到达理想和目的地,只有拼搏,才会获得辉煌的成功,只有播种,才会有收获。只有追求,才会品味堂堂正正的人。