1. <template>
  2. <button
  3. class="el-button"
  4. @click="handleClick"
  5. :disabled="buttonDisabled || loading"
  6. :autofocus="autofocus"
  7. :type="nativeType"
  8. :class="[
  9. type ? 'el-button--' + type : '',
  10. buttonSize ? 'el-button--' + buttonSize : '',
  11. {
  12. 'is-disabled': buttonDisabled,
  13. 'is-loading': loading,
  14. 'is-plain': plain,
  15. 'is-round': round,
  16. 'is-circle': circle
  17. }
  18. ]"
  19. >
  20. <i class="el-icon-loading" v-if="loading"></i>
  21. <i :class="icon" v-if="icon && !loading"></i>
  22. <span v-if="$slots.default"><slot></slot></span>
  23. </button>
  24. </template>
  25. <script>
  26. export default {
  27. name: 'ElButton',
  28. inject: {
  29. elForm: {
  30. default: ''
  31. },
  32. elFormItem: {
  33. default: ''
  34. }
  35. },
  36. props: {
  37. type: {
  38. type: String,
  39. default: 'default'
  40. },
  41. size: String,
  42. icon: {
  43. type: String,
  44. default: ''
  45. },
  46. nativeType: {
  47. type: String,
  48. default: 'button'
  49. },
  50. loading: Boolean,
  51. disabled: Boolean,
  52. plain: Boolean,
  53. autofocus: Boolean,
  54. round: Boolean,
  55. circle: Boolean
  56. },
  57. computed: {
  58. _elFormItemSize() {
  59. return (this.elFormItem || {}).elFormItemSize;
  60. },
  61. buttonSize() {
  62. return this.size || this._elFormItemSize || (this.$ELEMENT || {}).size;
  63. },
  64. buttonDisabled() {
  65. return this.disabled || (this.elForm || {}).disabled;
  66. }
  67. },
  68. methods: {
  69. handleClick(evt) {
  70. this.$emit('click', evt);
  71. }
  72. }
  73. };
  74. </script>
  1. methods: {
  2. handleClick(evt) {
  3. this.$emit('click', evt);
  4. }
  5. }

用 Vue 内置事件系统向父级()触发一个 click 事件

  1. <i class="el-icon-loading" v-if="loading"></i>
  2. <i :class="icon" v-if="icon && !loading"></i>
  3. <span v-if="$slots.default"><slot></slot></span>
  • 通过 props 来控制是否显示 i 标签
  • 用 $slots.default 来判断是否有子元素存在

    参考资料

  1. Element源码分析系列3-Button(按钮)