本篇文章為大家展示了如何在vue中使用rem適配移動端屏幕,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
安裝 postcss-pxtorem
npm install postcss-pxtorem --save
新建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()
}并引用進main.js文件內
import './rem'
修改.postcssrc.js 文件
在.postcssrc.js文件內的 plugins 添加以下配置,配后就可以在開發中直接使用 px 單位開發了
"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>效果

補充:下面看下Vue用rem布局
使用vue.js搭建一個移動端項目,怎樣做到自適應呢?當然選擇rem布局是比較方便快捷的。
在使用vue-cli搭建好項目框架后,在目錄結構的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>上述內容就是如何在vue中使用rem適配移動端屏幕,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。