0
点赞
收藏
分享

微信扫一扫

自定义mixin.less并全局注入至项目中


前言

有的时候写项目,需要一些通用的​​css​​样式来实现一些功能,比如居中、渐变、单行溢出省略号、多行溢出省略号等.

项目使用的​​less​​预处理器,所以整理了一些常见的​​mixin​​函数

实现

新建​​mixin.less​​文件,整理了一些笔者常用的几个,其他的可以自行添加

具体​​less​​​如何使用可以看​​https://www.w3cschool.cn/less/less_installation.html​​

.ellipsis() {
overflow: hidden;
-ms-text-overflow: ellipsis;
text-overflow: ellipsis;
white-space: nowrap;
}

//多行超出省略号
.ellipsisLine(@line : 2) {
word-break: break-all;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: @line;
overflow: hidden;
}

/*渐变(从上到下)*/
.linear-gradient(@direction:bottom, @color1:transparent, @color2:#306eff, @color3:transparent) {
//background: -webkit-linear-gradient($direction,$colorTop, $colorCenter, $colorBottom); /* Safari 5.1 - 6.0 */
background: -o-linear-gradient(@direction, @color1, @color2, @color3);
/* Opera 11.1 - 12.0 */
background: -moz-linear-gradient(@direction, @color1, @color2, @color3);
/* Firefox 3.6 - 15 */
background: linear-gradient(to @direction, @color1, @color2, @color3);
}

// 居中
.center(@width:null,@height:null) {
position: absolute;
top: 50%;
left: 50%;
& when (@width = null) and (@height= null){
transform: translate(-50%, -50%);
}
& when not(@width = null) and not(@height = null){
width: @width;
height: @height;
margin: -(@height / 2) 0 0 -(@width / 2);
}
& when not (@width = null) and (@height = null){
width: @width;
margin-left: -(@width / 2);
transform: translateY(-50%);
}
& when (@width = null) and not(@height=null){
height: @height;
margin-top: -(@height / 2);
transform: translateX(-50%);
}
}

使用

在项目页面中

@import 'mixin.less'
.main {
height: 100vh;
width: 100vw;
h2 {
color: @primary-color;
font-size: @font-size-lg;
}
}
.class {
.center(100px, 100px);
.linear-gradient();
.ellipsis();
}

预编译之后就变成

.main {
height: 100vh;
width: 100vw;

}
.main h2{
color: red;
font-size:16px;
}
.class {
position: absolute;
top: 50%;
left: 50%;
width: 2.66667rem;
height: 2.66667rem;
margin: -1.33333rem 0 0 -1.33333rem;
background: -webkit-linear-gradient(top, transparent, #306eff, transparent);
background: linear-gradient(to bottom, transparent, #306eff, transparent);
overflow: hidden;
-ms-text-overflow: ellipsis;
text-overflow: ellipsis;
white-space: nowrap;
}

优化

如果多个页面中都用到这个​​mixin.less​​​,我们需要在不同的​​less​​​文件下​​@import​

这是个很累的过程,我们可以借助万能的​​webpack​​去解决

笔者是基于​​vue-cli3​​新建的项目,所以这里以此环境表述

先安装​​style-resources-loader​

yarn add style-resources-loader

然后修改配置文件

// 全局注入theme.less
function addStyleResource (rule) {
rule.use('style-resource')
.loader('style-resources-loader')
.options({
patterns: [
path.resolve(__dirname, './src/assets/less/mixin.less'),
],
})
}
module.exports = {
chainWebpack(config) {
const types = ['vue-modules', 'vue', 'normal-modules', 'normal']
types.forEach(type => addStyleResource(config.module.rule('less').oneOf(type)))
}
}

注意配置文件中的那个文件地址就是我们需求全局引入的文件,记得修改之后重启服务使配置生效

重启完成之后,将每个页面中的​​@import​​删除掉,刷新页面,效果依然存在


举报

相关推荐

0 条评论