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、页面效果

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

相关推荐
汪子熙24 分钟前
Angular 服务器端应用 ng-state tag 的作用介绍
前端·javascript·angular.js
Envyᥫᩣ32 分钟前
《ASP.NET Web Forms 实现视频点赞功能的完整示例》
前端·asp.net·音视频·视频点赞
Мартин.4 小时前
[Meachines] [Easy] Sea WonderCMS-XSS-RCE+System Monitor 命令注入
前端·xss
昨天;明天。今天。6 小时前
案例-表白墙简单实现
前端·javascript·css
数云界6 小时前
如何在 DAX 中计算多个周期的移动平均线
java·服务器·前端
风清扬_jd6 小时前
Chromium 如何定义一个chrome.settingsPrivate接口给前端调用c++
前端·c++·chrome
安冬的码畜日常6 小时前
【玩转 JS 函数式编程_006】2.2 小试牛刀:用函数式编程(FP)实现事件只触发一次
开发语言·前端·javascript·函数式编程·tdd·fp·jasmine
ChinaDragonDreamer6 小时前
Vite:为什么选 Vite
前端
小御姐@stella6 小时前
Vue 之组件插槽Slot用法(组件间通信一种方式)
前端·javascript·vue.js
GISer_Jing6 小时前
【React】增量传输与渲染
前端·javascript·面试