Element UI For Vue 组件源码试读

还是从最简单的开始吧(博主较菜)~ el-button。

先回顾一下el-button的用法,我们尝试剥离一下它的 html,css,js。首先 el-buttonhtml基础构成,应该是一个可以嵌入图标原生的button按钮。当然,也可以有其它的解读。

<template>
  <button class="el-button">
    <i></i>  /*前缀icon*/
    <span></span> /*按钮上文字描述*/
  </button>
</template>

props绑定

这个按钮相比原生的,样式上可以有尺寸size,背景色type的设置,圆角round,包括前面的icon,这些都是实际开发者调用的时候根据需要设置的(外部通过props传参至组件)。所以props的设置上需要充分考虑不同场景下按钮的交互式样。

export default {
  props: {
    type: {type: String,default: ''},
    size: {type: String, default: 'medium'},
    icon: {type: String,default: ''},
    disabled: Boolean,
    plain: Boolean,
    round: Boolean
  }
}

propsstyle的绑定方法及类型检测可参见vue的官方文档

type ,size,disabled,plain,round所对应的CSS样式通过Class与上述参数绑定,
disabled等原生就有的交互样式则直接绑定

<template>
  <button 
    class="el-button"
    :disabled="disabled"
    :class="[
      type ? 'el-button--' + type : '',
      size ? 'el-button--' + size: '',
      {
        'is-disabled': buttonDisabled,
        'is-loading': loading,
        'is-plain': plain,
        'is-round': round,
      }
    ]">
    <i :class="icon"></i>  /*前缀icon*/
    <span></span> /*按钮上文字描述*/
  </button>
</template>

slot传参

按钮上的文字显示如何从父组件传递过来,当然是以slot插槽来实现。

<span><slot></slot></span> /*slot标签即被替换为 button上文字描述*/

事件处理

按钮必不可少的就是点击事件。因为click是button的原生就有的,所以<template>里使用@click 来触发点击事件,同时绑定的处理函数handleClick 通过emit将需要点击event传递出去。

<button
	@click="handleClick"
	...
>
</button>
handleClick(evt) {
	this.$emit('click', evt);
}

最简易的 el-button

<template>
  <button 
    class="el-button"
    :disabled="disabled"
    :class="[
      type ? 'el-button--' + type : '',
      size ? 'el-button--' + size: '',
      {
        'is-disabled': buttonDisabled,
        'is-loading': loading,
        'is-plain': plain,
        'is-round': round,
      }
    ]">
    <i :class="icon"></i>  /*前缀icon*/
    <span></span> /*按钮上文字描述*/
  </button>
</template>
<script>
  export default {
    name: 'ElButton',
    props: {
      type: {
        type: String,
        default: 'default'
      },
      size: String,
      icon: {
        type: String,
        default: ''
      },
      disabled: Boolean,
      plain: Boolean,
      round: Boolean,
    },
    methods: {
      handleClick(evt) {
        this.$emit('click', evt);
      }
    }
  };
</script>

当然 真实的el-button 还是比这个稍微复杂一些。比如外层form的样式继承。总之,三大样props,slot,emit基础把握住,组件的运用也不是那么晦涩的东西。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值