浅读一下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,不要到时候一脸懵逼
相关推荐
试图让你心动7 小时前
原生input添加删除图标类似vue里面移入显示删除[jquery]
前端·vue.js·jquery
_Kayo_7 小时前
VUE2 学习笔记6 vue数据监测原理
vue.js·笔记·学习
陈琦鹏7 小时前
轻松管理 WebSocket 连接!easy-websocket-client
前端·vue.js·websocket
小毛驴8508 小时前
创建 Vue 项目的 4 种主流方式
前端·javascript·vue.js
JSON_L12 小时前
Vue 电影导航组件
前端·javascript·vue.js
计算机编程果茶熊12 小时前
毕设选题难、不会写代码、答辩紧张?校园失物招领系统从需求到实现全流程指南|计算机毕业设计
java·vue.js
奇舞精选12 小时前
从零开始实现Vue3+WebAssembly万级数据表格开发流程
vue.js·webassembly
Britney⁺♛&?ꪶꪫꪜꫀ16 小时前
Vue2上
vue.js·npm
江城开朗的豌豆16 小时前
Element UI动态组件样式修改小妙招,轻松拿捏!
前端·javascript·vue.js
海天胜景19 小时前
vue3 el-table 列数据合计
前端·javascript·vue.js