Vue项目引入scss实现移动端适配
2020-03-21 本文已影响0人
Web_Fei
引入sass/scss(注意:项目已经搭建好)
如果npm太慢,国内建议使用淘宝镜像,安装cnpm
npm install -g cnpm --registry=https://registry.npm.taobao.org
安装后就可以用cnpm安装依赖包了
cnpm install sass-loader node-sass vue-style-loader --D
1.index.html添加mate标签
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1,minimum-scale=1,user-scalable=no">
2.app.vue文件中设置html的font-size动态转换方法
<script>
export default {
mounted() {
let htmlwidth = document.documentElement.clientWidth || document.body.clientWidth;
// 获取html的dom
let htmldom = document.getElementsByTagName('html')[0];
//设置html的font-size
htmldom.style.fontSize = htmlwidth / 10 + 'px';
window.addEventListener('resize', (e) => {
let htmlwidth = document.documentElement.clientWidth || document.body.clientWidth;
htmldom.style.fontSize = htmlwidth / 10 + 'px';
})
}
}
</script>
3.项目中新建base.scss文件
@function px2rem($px) {
@return ($px/ 75) + rem;
}
4.需要用到移动端适配的组件页面需要2个步骤:
①给组件style增加lang="scss"
<style lang="scss">
</style>
②引入之前新建的base.scss文件,主要用它的公式得出的rem来达到自适应的作用,以iPhone6为准,设计宽度为750px,那么根据设计图量多少,设置像素px2rem(量的值)!
<template>
<div>
<div id="cont">
<p class="nav"></p>
</div>
</div>
</template>
<script>export default {}</script>
<style lang="scss">
@import "../assets/css/base.scss";
#cont {
background-color: #b3d0db;
width: 100%;
height: 150px;
color: rgb(118, 152, 160);
}
.nav {
width: px2rem(375);
height: 100%;
margin: 0 auto;
background-color: #d7e5ef;
line-height: 150px;
}
</style>
最终效果如下
上面设置了.nav图层宽度为px2rem(375),因为总宽度为750,所以.nav不论在哪个移动设备下,宽度总保持窗口宽度一半。
