浅读一下element-plus源码 -- ElButton

写在前面

终于开始阅读element-plus的源码啦,不知道能坚持多久,希望自己继续加油啦,此篇是对我自己来说觉得有帮助的地方,如果知识点太过简单,见谅嘞。 源码对我觉得最有用的地方的话就是在:

  • 使用type限制String类型的使用,分为编译时和运行时
  • 使用provide/inject依赖注入实现统一化管理

一. 源码

克隆的是dev这个分支,最新的那个好多文件,让人害怕哈哈哈

js 复制代码
<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"
  >
    <i v-if="loading" class="el-icon-loading"></i>
    <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) {
    const $ELEMENT = useGlobalConfig()

    const elForm = inject(elFormKey, {} as ElFormContext)
    const elFormItem = inject(elFormItemKey, {} as ElFormItemContext)

    const buttonSize = computed(() => {
      return props.size || elFormItem.size || $ELEMENT.size
    })
    const buttonDisabled = computed(() => {
      return props.disabled || elForm.disabled
    })

    //methods
    const handleClick = evt => {
      ctx.emit('click', evt)
    }

    return {
      buttonSize,
      buttonDisabled,
      handleClick,
    }
  },
})
</script>

文档是最新版的,所以还有一些属性上面的代码中是没有的

文档介绍在这里:element-plus.org/zh-CN/compo...

很简单的一个组件,props,自定义事件,外加使用provide/inject实现按钮大小随表单或者全局配置大小改变而变化

二、有收获的地方

  1. 自定义type类型加断言实现字符串类型数据编译时验证,validator验证实现运行时验证
js 复制代码
...
type IButtonType = PropType<'primary'|'success'|'warning'|'danger'|'text'|'default'>
...
props: {
    type: {
      type: String as IButtonType,
      default: 'default',
      validator: (val: string) => {
        return [
          'default',
          'primary',
          'success',
          'warning',
          'info',
          'danger',
          'text',
        ].includes(val)
      },
    },
    ...
}
  • 对于String as IButtonType这,如果写的字符串不是IButtonType类型,那么编译器会报错(可以运行)
  • 而对于validator来说,如果只写了这个的情况下,那么当写的字符串不是IButtonType类型时,编译器不会报错,当运行后会有警告

自我感觉来看,第一种方式会更好些,非常明显的提示,而且会有代码提示,而第二种写完了才知道,还需要去看validator的情况才知道为啥错了,然后个人觉得两种都用有些多余,只用自定义type的类型就非常好了

  1. 使用provide/inject依赖注入实现统一化管理
js 复制代码
import { useGlobalConfig } from '@element-plus/utils/util'
import { elFormKey, elFormItemKey } from '@element-plus/form'
...
const $ELEMENT = useGlobalConfig()

const elForm = inject(elFormKey, {} as ElFormContext)
const elFormItem = inject(elFormItemKey, {} as ElFormItemContext)

const buttonSize = computed(() => {
  return props.size || elFormItem.size || $ELEMENT.size
})
const buttonDisabled = computed(() => {
  return props.disabled || elForm.disabled
})

这里通过依赖注入的方式实现了让按钮在没有设置大小的情况下遵循表单的大小(若有,不然就是全局配置的大小),以及设置按钮是否可用

因此这里可以看出我们在使用ElButton时,表单的大小和是否禁用状态是会影响ElButton状态的,当然ElButton它有自己的想法那就没办法啦。

这里关于provide/inject的使用推荐:juejin.cn/post/684490...

自我感觉关于页面主题切换这个功能用这个来写就非常不错,不过平时开发也确实不多,还是大佬说的用于组件开发比较合适。

三. 对开发的帮助

  1. 如果想要写的组件是固定类型值类型的字符串,那就设置定义一个type
  2. 使用开源组件的时候,注意祖宗组件对子组件的影响,可能源码里使用了provide/inject,不要到时候一脸懵逼
相关推荐
Jiaberrr3 小时前
前端实战:使用JS和Canvas实现运算图形验证码(uniapp、微信小程序同样可用)
前端·javascript·vue.js·微信小程序·uni-app
LvManBa3 小时前
Vue学习记录之六(组件实战及BEM框架了解)
vue.js·学习·rust
200不是二百3 小时前
Vuex详解
前端·javascript·vue.js
LvManBa4 小时前
Vue学习记录之三(ref全家桶)
javascript·vue.js·学习
深情废杨杨4 小时前
前端vue-父传子
前端·javascript·vue.js
工业互联网专业5 小时前
毕业设计选题:基于springboot+vue+uniapp的驾校报名小程序
vue.js·spring boot·小程序·uni-app·毕业设计·源码·课程设计
J不A秃V头A5 小时前
Vue3:编写一个插件(进阶)
前端·vue.js
司篂篂5 小时前
axios二次封装
前端·javascript·vue.js
姚*鸿的博客6 小时前
pinia在vue3中的使用
前端·javascript·vue.js
天下无贼!7 小时前
2024年最新版Vue3学习笔记
前端·vue.js·笔记·学习·vue