vue-cli3.0 使用px2rem 或 postcss-plugin-px2rem
px2rem
-
構建項目(vue-cli3.0)
vue create hello-world (Manuall select features)
-
安裝px2rem-loader(devDependencies)
npm install px2rem-loader --save-dev
-
移動端適配解決npm包 "lib-flexible" (dependencies)
npm install lib-flexible --save
-
main.js中引入 "lib-flexible"
import 'lib-flexible' // 移動端適配 (目錄: hello-world/src/main.js)
-
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 }) <!--新增結束--> } }
-
在.vue中根據750px設計圖寫頁面
<style scoped> .wrap { background: #666666; height: 100px; } </style> iphone6: height: 1.3333rem
--此時是已經成功了,但是px2rem-loader這里只能僅限於css,並不能滿足大多數開發需求,比如使用less,stylus,scss...這個時候就需要postcss--
postcss-plugin-px2rem
---在上個例子基礎上---
-
安裝 "postcss-plugin-px2rem" (devDependencies)
npm install postcss-plugin-px2rem --save-dev
-
vue.config.js 配置 postcss-plugin-px2rem
module.exports = {
lintOnSave: true,
<!--新增的內容-->
css: {
loaderOptions: {
postcss: {
plugins: [
require('postcss-plugin-px2rem')({
rootValue: 75, //換算基數, 默認100 ,這樣的話把根標簽的字體規定為1rem為50px,這樣就可以從設計稿上量出多少個px直接在代碼中寫多上px了。
// unitPrecision: 5, //允許REM單位增長到的十進制數字。
//propWhiteList: [], //默認值是一個空數組,這意味着禁用白名單並啟用所有屬性。
// propBlackList: [], //黑名單
exclude: /(node_module)/, //默認false,可以(reg)利用正則表達式排除某些文件夾的方法,例如/(node_module)\/如果想把前端UI框架內的px也轉換成rem,請把此屬性設為默認值
// selectorBlackList: [], //要忽略並保留為px的選擇器
// ignoreIdentifier: false, //(boolean/string)忽略單個屬性的方法,啟用ignoreidentifier后,replace將自動設置為true。
// replace: true, // (布爾值)替換包含REM的規則,而不是添加回退。
mediaQuery: false, //(布爾值)允許在媒體查詢中轉換px。
minPixelValue: 3 //設置要替換的最小像素值(3px會被轉rem)。 默認 0
}),
]
}
}
}
<!--新增結束-->
}
package.json 中加入postcss 相關插件
{
"dependencies": { .. }
"postcss": {
"plugins": {
"autoprefixer": {},
"precss": {}
}
}
}