自定义mixin.less并全局注入至项目中
2019-12-06 本文已影响0人
w候人兮猗
前言
有的时候写项目,需要一些通用的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
删除掉,刷新页面,效果依然存在
关于
- 本文首发于自定义mixin.less并全局注入至项目中
- 参考文章:Vue-cli3-自动化导入