vue使用rem實現 移動端屏幕適配


要想移動端適配 並使用 rem  您需要先看這篇文章,配置好less ➡️ 在vue 中使用 less,就可以使用rem了

如果項目已經開發的差不多了,沒有用到rem 又要使用rem,您用這招。

postcss-pxtorem:轉換px為rem的插件

安裝 postcss-pxtorem

前端精品教程:百度網盤下載

npm install postcss-pxtorem --save

 

新建rem.js文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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 單位開發了

?
1
2
3
4
"postcss-pxtorem" : {
  "rootValue" : 32,
  "propList" : [ "*" ]
}

helloworld.vue

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<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文件中添加一段代碼:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<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>

之后,在寫css時,只要將px單位替換成rem,這里設置的比例是100px=1rem,例如,寬度為100px時,可以直接寫成1rem。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM