改变iVIew默认样式的方法

改变iVIew默认样式的方法

自定义指令v-scoped

改变的样式只在单个文件中生效,不污染全局样式。

封装

@/directives/v-scoped.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
var install = {
install(Vue) {
var directiveFun = {
eachChild(el, scoped) {
if (!(el instanceof HTMLElement)) return;
scoped.forEach(name => {
el.setAttribute(name, '');
});
if (el.childNodes.length) {
for (var i = 0; i < el.childNodes.length; i++) {
directiveFun.eachChild(el.childNodes[i], scoped);
}
}
},
getParentScoped(dom, layer) {
function getScoped(dom) {
var scoped = [];
for (var i = 0; i < dom.attributes.length; i++) {
var nodedate = dom.attributes[i];
if (nodedate && String(nodedate.nodeName).substr(0, 7) === 'data-v-') {
scoped.push(nodedate.nodeName);
}
}
return scoped;
}
if (!dom) return;
var domLayer = isNaN(layer) ? 0 : parseInt(layer);
var scoped = [];
var parent = dom;
do {
var scopedList = getScoped(parent);
scoped = scoped.concat(scopedList);
parent = parent.parentNode;
domLayer--;
} while (parent && domLayer > 0);
return scoped;
}
};
// 全局注册 自定义指令
Vue.directive('scoped', {
inserted: function(el) {
var scoped = directiveFun.getParentScoped(el, 2);
if (scoped.length) {
directiveFun.eachChild(el, scoped); //批量追加
}
}
});
}
};
export default install;

@/directives/index.js:

1
2
3
4
import vScoped from './v-scope';
import Vue from 'vue';

Vue.use(vScoped);

注册自定义指令:

@/idnex.js:

1
2
// 导入自定义指令 index.js 会使用Vue.use()来注册指令
import '@/directives';

用法

  1. F12找到含有data-vdom,手动添加class
  2. 在含有scopedstyle里写上样式
1
2
3
<Select class="nameOne" v-scoped>

</Select>
1
2
3
4
5
<style scoped>
.nameOne .ivu-select-dropdown {
top: 34px;
}
</style>

style不加scoped

另一种方法是另写一个style,不加scoped,将要重写的iView写在其中。

但这样有一个缺点:定义的类名可能会污染全局样式。

因此必须保证手动添加的类名独一无二。

/deep/穿透

直接通过检查元素找到className

1
2
3
4
5
6
7
8
9
/deep/.vux-label::before {
content: '*';
display: inline-block;
margin-right: 4px;
line-height: 1;
font-family: SimSun;
font-size: 12px;
color: #ed3f14;
}

注意:在less中,deep不能在嵌套写法中穿透2层,因此需要分开写2段

全局的iView样式

可以全局更改iView样式。

@/style/public.less:

1
2
3
4
5
6
7
8
@import url('../../../node_modules/iview/src/styles/index.less');

.select30 .ivu-select-dropdown {
top: 30px !important;
}
.search-bg .ivu-form-item{
margin-bottom: 5px !important;
}

@/index.js:

1
import '@/styles/public.less';