vue项目实现屏幕自适应,亲测适配...

304 阅读1分钟

1.安装命令

npm install postcss-px2rem px2rem-loader --save

2.在src目录下util中新建js配置文件

// rem等比适配配置文件  
// 基准大小  
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()  
}

3.在main.js中引入配置文件

import "./util/rem"; // 自适应分辨率

4.在vue.config.js中配置插件

// 引入等比适配插件  
const px2rem = require('postcss-px2rem')  
// 配置基本大小  
const postcss = px2rem({  
// 基准大小 baseSize,需要和rem.js中相同  
remUnit: 16  
})
module.exports = {  
publicPath: "/",  
assetsDir: 'static',  
productionSourceMap: true,  
configureWebpack: {  
devtool: 'source-map'  
},  
devServer: {  
port: 27101,  
// proxy: {  
// "/api": {  
// // 代理名称 凡是使用/api开头的地址都是用此代理  
// target: "http://20.38.146.34:27001/", // 需要代理访问的api地址  
// // target: "http://www.tianqiapi.com/", // 需要代理访问的api地址  
// changeOrigin: true, // 允许跨域请求  
// ws: true,  
// pathRewrite: {  
// // 重写路径,替换请求地址中的指定路径  
// "^/api": "", // 将请求地址中的/api替换为空,也就是请求地址中不会包含/api/  
// },  
// },  
// "/user1": {  
// // 代理名称 凡是使用/api开头的地址都是用此代理  
// // target: "http://20.38.81.81:27093/", // 需要代理访问的api地址  
// target: "http://20.38.81.81:27093/", // 需要代理访问的api地址http://20.38.81.81:27096/  
// changeOrigin: true, // 允许跨域请求  
// ws: true,  
// pathRewrite: {  
// // 重写路径,替换请求地址中的指定路径  
// "^/user1": "", // 将请求地址中的/api替换为空,也就是请求地址中不会包含/api/  
// },  
// }  
// }  
},  
// 使用等比适配插件  
lintOnSave: true,  
css: {  
    loaderOptions: {  
        postcss: {  
            plugins: [  
                postcss  
                ]  
            }  
        }  
    }  
}

持续更新中...