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

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

相关推荐
南屿欣风4 分钟前
解决 Gin Web 应用中 Air 热部署无效的问题
前端·gin
猿大师办公助手7 分钟前
Web网页内嵌福昕OFD版式办公套件实现在线预览编辑PDF、OFD文档
前端·pdf·word
幼儿园技术家1 小时前
什么是RESTful 或 GraphQL?
前端
Lonwayne1 小时前
当编程语言有了人格
java·javascript·c++·python·php
echola_mendes1 小时前
LangChain 结构化输出:用 Pydantic + PydanticOutputParser 驯服 LLM 的“自由发挥”
服务器·前端·数据库·ai·langchain
拉不动的猪2 小时前
刷刷题46(常见的三种js继承类型及其优缺点)
前端·javascript·面试
关注我:程序猿之塞伯坦2 小时前
JavaScript 性能优化实战:突破瓶颈,打造极致 Web 体验
开发语言·前端·javascript
兰德里的折磨5502 小时前
对于后端已经实现逻辑了,而前端还没有设置显示的改造
前端·vue.js·elementui
hikktn2 小时前
【开源宝藏】30天学会CSS - DAY9 第九课 牛顿摆动量守恒动画
前端·css·开源
悦涵仙子3 小时前
NG-ZORRO中tree组件的getCheckedNodeList怎么使用
javascript·ecmascript·angular.js