拜读及分析Element源码-button组件篇

button组件开发时用到的频率非常高,一起来看看吧。

button组件相关的有两个文件

button-group(按钮组)

按钮组时使用,相当于button的一个父容器,内包含一个匿名插槽,具体的处理在button.vue中

1
2
3
4
5
6
7
8
9
10
<template>
<div class="el-button-group">
<slot></slot>
</div>
</template>
<script>
export default {
name: 'ElButtonGroup'
};
</script>

button (按钮)

结构

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
<button
class="el-button"
@click="handleClick"
:disabled="buttonDisabled || loading"
:autofocus="autofocus"
:type="nativeType"
:class="[
type ? 'el-button--' + type : '',
buttonSize ? 'el-button--' + buttonSize : '',
{
'is-disabled': buttonDisabled,
'is-loading': loading,
'is-plain': plain,
'is-round': round,
'is-circle': circle
}
]"
>
<!-- loading -->
<i class="el-icon-loading" v-if="loading"></i>
<!-- icon -->
<i :class="icon" v-if="icon && !loading"></i>
<!-- 插槽 -->
<span v-if="$slots.default"><slot></slot></span>
</button>
  • button按钮
    • 属性:
      • disabled:是否禁用
      • autofocus:是否获取焦点
      • type:赋值button的原生type(props中接收的nativeType)
      • class: 多条件动态显示(此处用数组嵌套对象的写法 点击跳转官方文档
  • loading:props接收的loading为真时显示。
  • icon:props接收的icon为真并且loading为假时显示。
  • 插槽:接收到匿名插槽内容时显示。(也就是使用button-group按钮组时)

inject: 接收form组件注入的属性

1
2
3
4
5
6
7
8
inject: {
elForm: {
default: ''
},
elFormItem: {
default: ''
}
}

这里接收默认为空

如果button组件在form组件内使用,若form向子孙后代注入某些属性。会影响button的一些样式(本组件computed 中可以看到)。

点击查看官方文档: provide 和 inject

那么问题来了,有props为什么还要用 provide 和 inject 呢,因为前者只能用于父子,后者可以子孙后代,层级更深

computed

1
2
3
4
5
6
7
8
9
10
11
12
13
computed: {
_elFormItemSize() {
return (this.elFormItem || {}).elFormItemSize;
},
// 大小样式由props接收的size和formItem组件注入的size以及全局配置对象($ELEMENT,此对象由引入时Vue.use()传入的默认空对象)的size决定
buttonSize() {
return this.size || this._elFormItemSize || (this.$ELEMENT || {}).size;
},
// props接收disabled以及form组件注入的disabled决定(loading时也禁止↑)
buttonDisabled() {
return this.disabled || (this.elForm || {}).disabled;
}
}
  • size的影响因素

    • props接收的size

    • form组件provide 的size

    • 全局配置对象$ELEMENT的size: vue.use()时传入的

      1
      2
      3
      import Vue from 'vue';
      import Element from 'element-ui';
      Vue.use(Element, { size: 'small', zIndex: 3000 });
  • disabled的影响因素

    • props接收的disabled

    • form组件provide 的disabled

事件methods

1
2
3
4
5
6
methods: {
// 点击button向父组件暴露点击事件
handleClick(evt) {
this.$emit('click', evt);
}
}

props

可以结合element文档看

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
props: {
// 按钮主题样式
type: {
type: String,
default: 'default'
},
// 按钮大小
size: String,
// icon
icon: {
type: String,
default: ''
},
// 原生button属性
nativeType: {
type: String,
default: 'button'
},
// 按钮的loding动画
loading: Boolean,
// 禁用
disabled: Boolean,
// 朴素样式
plain: Boolean,
// 聚焦
autofocus: Boolean,
// 圆角
round: Boolean,
// 圆形
circle: Boolean
}

学习

------ 本文结束------
0%