vue中rem的配置的方法示例
在用vue或react等工具搭建一個移動端項目時,怎樣做到自適應(yīng)呢? 當(dāng)然選擇rem布局比較方便快捷.
開發(fā)移動端,我們常常要用到rem+flex,那么vue中如何配置呢,我的做法是這樣:
1、在js中統(tǒng)一計算配置
代碼如下:
export default function() {
// var devicePixelRatio = 1;
// var scale = 1 / devicePixelRatio;
// document.querySelector('meta[name="viewport"]').setAttribute('content','initial-scale=' + scale + ', maximum-scale=' + scale + ', minimum-scale=' + scale + ', user-scalable=no');
// 7.5根據(jù)設(shè)計稿的橫向分辨率/100得來
// alert(document.documentElement.clientWidth)
var deviceWidth = document.documentElement.clientWidth;
// var deviceWidth = window.screen.availWidth
// alert(navigator.userAgent)
// alert(deviceWidth)
// console.log(navigator.userAgent)
if(deviceWidth > 750) {
// deviceWidth = 750;
deviceWidth = 7.5 * 50;
}
document.documentElement.style.fontSize = deviceWidth / 7.5 + 'px';
// 禁止雙擊放大
document.documentElement.addEventListener('touchstart', function (event) {
if (event.touches.length > 1) {
event.preventDefault();
}
}, false);
var lastTouchEnd = 0;
document.documentElement.addEventListener('touchend', function (event) {
var now = Date.now();
if (now - lastTouchEnd <= 300) {
event.preventDefault();
}
lastTouchEnd = now;
}, false);
}
然后在main.js中引入使用。

結(jié)構(gòu)

main.js
然后在index.css中設(shè)置默認(rèn)大小:

基礎(chǔ)css
index.scss一般也在main.js里面引入:

main.js
2、借助px2rem 插件
安裝
npm install px2rem-loader lib-flexible --save
在項目入口文件main.js中引入lib-flexible
import 'lib-flexible/flexible.js'
在build下的 utils.js中,找到generateLoaders 方法,在這里添加 。
const px2remLoader = {
loader: 'px2rem-loader',
options: {
remUnit: 37.5
}
}
function generateLoaders (loader, loaderOptions) {
const loaders = [cssLoader, px2remLoader]
if (loader) {
loaders.push({
loader: loader + '-loader',
options: Object.assign({}, loaderOptions, {
sourceMap: options.sourceMap
})
})
}
重啟項目,會發(fā)現(xiàn)自己設(shè)置的px被轉(zhuǎn)為rem 了

效果
以上實現(xiàn)轉(zhuǎn)換適用于:
(1)組件中編寫的<style></style>下的css
(2)從index.js或者main.js中import ‘../../static/css/reset.css'引入css
(3)在組件的<script type=”text/ecmascript-6″> import ‘../../static/css/reset.css'</script>中引入css
另外的情況不適用:
(1)組件<style></style>中@import “../../static/css/reset.css (可考慮上面(2)、(3)的形式引入)
(2)外部樣式:<link rel=”stylesheet” href=”static/css/reset.css”>
(3)元素內(nèi)部樣式:style=”height: 417px; width: 550px;”
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
element的el-upload組件上傳文件跨域問題的幾種解決
跨域問題網(wǎng)上搜索很多,感覺情況都不一樣,本文主要介紹了element的el-upload組件上傳文件跨域問題的幾種解決,具有一定的參考價值,感興趣的可以了解一下2024-03-03
詳解Vue CLI3配置之filenameHashing使用和源碼設(shè)計使用和源碼設(shè)計
這篇文章主要介紹了詳解Vue CLI3配置之filenameHashing使用和源碼設(shè)計使用和源碼設(shè)計,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-08-08

