本篇文章为大家展示了如何在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适配移动端屏幕,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。