element-ui button 仿写 demo

基于上篇 button 源码分享写了一个简单 demo,在写 demo 的过程中,又发现了一个小细节,分享一下:

1、组件部分:

html 复制代码
<template>
  <button
    class="yss-button"
    @click="handleClick"
    :class="[
      type ? 'yss-button--' + type : '',
      size ? 'yss-button--' + size : ''
    ]"
  >
    <span v-if="$slots.default"><slot></slot></span>
  </button>
</template>
<script>
export default {
  name: 'YssButton',
  props: {
    type: {
      type: String,
      default: 'default'
    },
    size: String,
    icon: {
      type: String,
      default: ''
    },
    circle: Boolean
  },

  methods: {
    handleClick(evt) {
      this.$emit('click', evt);
    }
  }
};
</script>

<style scoped>
.yss-button {
  display: inline-block;
  line-height: 1;
  white-space: nowrap;
  cursor: pointer;
  background: #fff;
  border: 1px solid #dcdfe6;
  color: #606266;
  -webkit-appearance: none;
  text-align: center;
  box-sizing: border-box;
  outline: none;
  margin: 0;
  transition: 0.1s;
  font-weight: 500;
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
  padding: 12px 20px;
  font-size: 14px;
  border-radius: 4px;
}

.yss-button--primary {
  color: #fff;
  background-color: #409eff;
  border-color: #409eff;
}

.yss-button--success {
  color: #fff;
  background-color: #67c23a;
  border-color: #67c23a;
}

.yss-button--warning {
  color: #fff;
  background-color: #e6a23c;
  border-color: #e6a23c;
}

.yss-button.is-circle {
  border-radius: 50%;
  padding: 12px;
}
</style>

2、使用部分

html 复制代码
<template>
  <div class="demo">
    <yss-button>默认按钮</yss-button>
    <yss-button type="primary">主要按钮</yss-button>
    <yss-button type="success">成功按钮</yss-button>
  </div>
</template>

<script>
export default {
  name: 'demo',
  methods: {
    handleClick() {
      console.log('test...');
    }
  }
};
</script>

3、发现的小问题:如果按我常有的思维逻辑,我会再增加一个属性来控制挂载内容是否展示,而源码当中的使用 $slots.default 这种方式来控制是否展示挂载内容就很好,很完美的少传了一个属性。

4、页面效果

总结:学完一个组件的源码之后,在学习的过程中,会尝试找出它的每个属性,每个方法的一个用途,但过于探索它的用途之后,有时会陷入为研究源码而研究源码的小陷阱,忘记将它带入自己的工作场景进行比对,从而错过了感受它真正的美。如果在研究完源码之后,尝试使用自己的思维方式去写一下试试,哪怕只是把源码改吧改吧跑成功呢,也能在这个过程中有一个全新的收获。

相关推荐
白嫖叫上我2 小时前
Vue3封装主题色完善版
前端
a1117762 小时前
细胞结构实验室(react 开源)
前端·javascript·开源·html
aaaak_2 小时前
PDD 直播间 评论 , wss hex Protobuf 解析流程分析学习
java·前端·学习
ikoala2 小时前
用了几周明基 RD280UG,我终于明白程序员为什么需要一台“专用显示器”
前端·后端·程序员
Dxy12393102162 小时前
JS如何获取元素高度
开发语言·javascript·ecmascript
文心快码BaiduComate2 小时前
Comate搭载DeepSeek-V4
前端·后端
豹哥学前端2 小时前
5分钟搞懂事件委托
前端·javascript·面试
Awu12272 小时前
🍎把数学公式搬进 Web 表格:一个 VTable 实战案例
前端
江无行者2 小时前
aly oss技能应用
前端
朝阳392 小时前
单向数据流
前端