version:element-plus 1.0.1-beta.0
<template>
<button
:class="[
'el-button',
type ? 'el-button--' + type : '',
buttonSize ? 'el-button--' + buttonSize : '',
{
'is-disabled': buttonDisabled,
'is-loading': loading,
'is-plain': plain,
'is-round': round,
'is-circle': circle
}
]"
:disabled="buttonDisabled || loading"
:autofocus="autofocus"
:type="nativeType"
@click="handleClick"
>
<!-- loading -->
<i v-if="loading" class="el-icon-loading"></i>
<!-- icon 总是在插槽前 显示在文字后的icon都是在插槽内实现的 -->
<i v-if="icon && !loading" :class="icon"></i>
<!-- 默认插槽 -->
<span v-if="$slots.default"><slot></slot></span>
</button>
</template>
<script lang='ts'>
import { computed, inject, defineComponent } from 'vue'
import { useGlobalConfig } from '@element-plus/utils/util'
import { isValidComponentSize } from '@element-plus/utils/validators'
import { elFormKey, elFormItemKey } from '@element-plus/form'
import type { PropType } from 'vue'
import type { ElFormContext, ElFormItemContext } from '@element-plus/form'
type IButtonType = PropType<'primary' | 'success' | 'warning' | 'danger' | 'info' | 'text' | 'default'>
type IButtonNativeType = PropType<'button' | 'submit' | 'reset'>
interface IButtonProps {
type: string
size: string
icon: string
nativeType: string
loading: boolean
disabled: boolean
plain: boolean
autofocus: boolean
round: boolean
circle: boolean
}
type EmitFn = (evt: Event) => void
export default defineComponent({
name: 'ElButton',
props: {
type: {
type: String as IButtonType,
default: 'default',
validator: (val: string) => {
return [
'default',
'primary',
'success',
'warning',
'info',
'danger',
'text',
].includes(val)
},
},
size: {
type: String as PropType<ComponentSize>,
validator: isValidComponentSize,
},
icon: {
type: String,
default: '',
},
nativeType: {
type: String as IButtonNativeType,
default: 'button',
validator: (val: string) => {
return ['button', 'submit', 'reset'].includes(val)
},
},
loading: Boolean,
disabled: Boolean,
plain: Boolean,
autofocus: Boolean,
round: Boolean,
circle: Boolean,
},
emits: ['click'],
setup(props, ctx) {
// 拿到全局的element的全局配置
const $ElEMENT = useGlobalConfig()
// 拿到 form 中注入的对象
const elForm = inject(elFormKey, {} as ElFormContext)
// 拿到 formItem 中注入的对象
const elFormItem = inject(elFormItemKey, {} as ElFormItemContext)
// 优先级 props > formItem > 全局配置
const buttonSize = computed(() => {
return props.size || elFormItem.size || $ElEMENT.size
})
// 优先级 props > form
// 这里可以记一下,我之前都是form中的每个组件绑一个 disabled 属性,然后修改绑定值
const buttonDisabled = computed(() => {
return props.disabled || elForm.disabled
})
//methods
// click 回调
const handleClick = evt => {
ctx.emit('click', evt)
}
return {
buttonSize,
buttonDisabled,
handleClick,
}
},
})
</script>