要想移動(dòng)端適配 并使用 rem 您需要先看這篇文章,配置好less ➡️ 在vue 中使用 less,就可以使用rem了
如果項(xiàng)目已經(jīng)開(kāi)發(fā)的差不多了,沒(méi)有用到rem 又要使用rem,您用這招。
postcss-pxtorem:轉(zhuǎn)換px為rem的插件
安裝 postcss-pxtorem
npm install postcss-pxtorem --save
新建rem.js文件
const baseSize = 32 // 設(shè)置 rem 函數(shù) function setRem () { // 當(dāng)前頁(yè)面寬度相對(duì)于 750 寬的縮放比例,可根據(jù)自己需要修改。 const scale = document.documentElement.clientWidth / 750 // 設(shè)置頁(yè)面根節(jié)點(diǎn)字體大小 document.documentElement.style.fontSize = (baseSize * Math.min(scale, 2)) + 'px' } // 初始化 setRem() // 改變窗口大小時(shí)重新設(shè)置 rem window.onresize = function () { setRem() }
并引用進(jìn)main.js文件內(nèi)
import './rem'
修改.postcssrc.js 文件
在.postcssrc.js文件內(nèi)的 plugins 添加以下配置,配后就可以在開(kāi)發(fā)中直接使用 px 單位開(kāi)發(fā)了
"postcss-pxtorem": { "rootValue": 32, "propList": ["*"] }
helloworld.vue
<template> <div class="hello"> test </div> </template> <script> export default { name: 'HelloWorld', data() { return { msg: 'Welcome to Your Vue.js App' } } } </script> <style scoped> .hello { text-align: center; font-size: 20px; width: 300px; height: 400px; background:red; } </style>
效果
補(bǔ)充:下面看下Vue用rem布局
使用vue.js搭建一個(gè)移動(dòng)端項(xiàng)目,怎樣做到自適應(yīng)呢?當(dāng)然選擇rem布局是比較方便快捷的。
在使用vue-cli搭建好項(xiàng)目框架后,在目錄結(jié)構(gòu)的index.html文件中添加一段代碼:
<script> fnResize() window.onresize = function () { fnResize() } function fnResize() { var deviceWidth = document.documentElement.clientWidth || window.innerWidth if (deviceWidth >= 750) { deviceWidth = 750 } if (deviceWidth <= 320) { deviceWidth = 320 } document.documentElement.style.fontSize = (deviceWidth / 7.5) + 'px' } </script>
之后,在寫(xiě)css時(shí),只要將px單位替換成rem,這里設(shè)置的比例是100px=1rem,例如,寬度為100px時(shí),可以直接寫(xiě)成1rem。
總結(jié)
以上所述是小編給大家介紹的vue使用rem實(shí)現(xiàn) 移動(dòng)端屏幕適配 ,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com