vue中使用less
(首先vue开发环境已安装成功)
在项目目录下安装 less 和 less-loader。
npm install less less-loader --save-dev
安装成功后,打开 build/webpack.base.conf.js ,在 module.exports = 的对象的 module.rules 后面添加一段:
module.exports = {
// 此处省略已有的的其他的内容
module: {
rules: [
// 此处省略已有的的其他的规则
{
test: /\.less$/,
loader: "style-loader!css-loader!less-loader"
}
]
}
}
最后,在代码中的 style 标签中 加上 lang=“less” 属性即可
<style scoped lang="less">
.div1 {
width: 200px;
height: 200px;
.div2 {
width: 100px;
height: 100px;
}
}
</style>
scoped 为只在此作用域有效
配置好less,就可以使用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>
之后,在写css时,只要将px单位替换成rem,这里设置的比例是100px=1rem,例如,宽度为100px时,可以直接写成1rem。
除了在index.html中插入如上代码,
还有另一种方式,安装转换px为rem的插件,postcss-pxtorem
安装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
文件内的 plugins
添加以下配置,配后就可以在开发中直接使用 px 单位开发了
"postcss-pxtorem": {
"rootValue": 32,
"propList": ["*"]
}