4

vue项目PC端如何适配不同分辨率屏幕 - 爱喝酸奶的吃货

 1 year ago
source link: https://www.cnblogs.com/yingzi1028/p/17180872.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

vue项目PC端如何适配不同分辨率屏幕

年前小颖第一家公司同事问我有做过pc端适配的项目吗,我给妹纸说了下,结果发现没说完,自己当时也没想起来,今天干脆总结下,方便自己和大家日后查看

安装postcss-px2rem、px2rem-loader

打开命令行工具,输入以下指令安装插件

npm install postcss-px2rem px2rem-loader --save

安装完后package.json文件会多如图俩插件

813088-20230305162128215-1974020889.png

在根目录src中新建utils目录下新建rem.js等比适配文件

const baseSize = 16
// 设置 rem 函数
function setRem() {
    // 当前页面宽度相对于 1920宽的缩放比例,可根据自己需要修改。
    const scale = document.documentElement.clientWidth / 1920
    // 设置页面根节点字体大小(“Math.min(scale, 2)” 指最高放大比例为2,可根据实际业务需求调整)
    document.documentElement.style.fontSize = baseSize * Math.min(scale, 2) + 'px'
}
// 初始化
setRem()
// 改变窗口大小时重新设置 rem
window.onresize = function () {
    setRem()
}

在main.js中引入适配文件

import './utils/rem'

vue.config.js文件中配置插件

// 引入等比适配插件
const px2rem = require('postcss-px2rem')
// 配置基本大小
const postcss = px2rem({
  // 基准大小 baseSize,需要和rem.js中相同
  remUnit: 16
})
 
// 使用等比适配插件
module.exports = {
  lintOnSave: true,
  css: {
    loaderOptions: {
      postcss: {
        plugins: [
          postcss
        ]
      }
    }
  }
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK