vue px转rem配置详解

Tricia ·
更新时间:2024-09-20
· 669 次阅读

目录

方法一

一、配置与安装步骤:

方法二

方法三

总结

方法一 一、配置与安装步骤:

1、在 Vue 项目的 src 文件夹下创建一个 config 文件夹:

2、在 config 文件夹中创建 rem.js:


3、将以下代码复制到 rem.js 中:

// 基准大小 const baseSize = 32 // 设置 rem 函数 function setRem () { // 当前页面宽度相对于 750 宽的缩放比例,可根据自己需要修改。 const scale = document.documentElement.clientWidth / 750 // 设置页面根节点字体大小 document.documentElement.style.fontSize = (baseSize * Math.min(scale, 2)) + 'px' } // 初始化 setRem() // 改变窗口大小时重新设置 rem window.onresize = function () { setRem() }

4、在 src 文件夹下的 main.js 中引入:

import './config/rem'

5、在 Vue 项目根目录终端引入:

npm install postcss-pxtorem -D

6、在 Vue 项目文件夹下的 postcss.config.js 中加入:

module.exports = { plugins: { autoprefixer: {}, "postcss-pxtorem": { "rootValue": 16, "propList": ["*"] } } } 方法二

第一步 安装 lib-flexible

npm i lib-flexible --save

第二步 安装 px2rem-loader

npm install px2rem-loader --save-dev

第三步 引入lib-flexible

import 'lib-flexible/flexible'

第四步 最重要的一步 配置utils文件

const px2remLoader = { loader: 'px2rem-loader', options: { remUnit: 37.5 } }<br>//在generateLoaders方法中添加px2remLoader 1 const loaders = [cssLoader,px2remLoader]

或者第四步:Create new “vue.config.js” file if without “vue.config.js” (目录: hello-world/vue.config.js)

module.exports = { chainWebpack: (config) => { config.module .rule('css') .test(/\.css$/) .oneOf('vue') .resourceQuery(/\?vue/) .use('px2rem') .loader('px2rem-loader') .options({ remUnit: 75 // 75表示750的设计稿,37.5表示375的设计稿 }) } }

1.按照px来编写都会转化成rem的形式,但是有些地方我们不想转换,可以用下面两种方法。

在px后面添加/no/,不会转化px,会原样输出。 — 一般border需用这个
在px后面添加/px/,会根据dpr的不同,生成三套代码。---- 一般字体需用这个

2 使用过程中,发现某些import外联样式不会被转化,注意避开这些坑。

<style src='../assets/style.css'> /* px2rem能正常转换 */ </style> <style> /* px2rem不能正常转换 */ @import '../assets/style.css'; </style> <style> /* px2rem不能正常转换 */ @import url('../assets/style.css'); </style> 方法三

第一步 安装 amfe-flexible

npm i amfe-flexible -S

第二步 安装 postcss-pxtorem

npm install postcss-pxtorem --save-dev

第三步 引入amfe-flexible

import 'amfe-flexible'

第四步根目录下创建postcss.config.js文件

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

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注软件开发网的更多内容!



VUE px rem

需要 登录 后方可回复, 如果你还没有账号请 注册新账号