草庐IT

记录--elementui源码学习之仿写一个el-button

林恒 2023-03-28 原文

这里给大家分享我在网上总结出来的一些知识,希望对大家有所帮助

本篇文章记录仿写一个el-button组件细节,从而有助于大家更好理解饿了么ui对应组件具体工作细节。本文是elementui源码学习仿写系列的又一篇文章,后续空闲了会不断更新并仿写其他组件。源码在github上,大家可以拉下来,npm start运行跑起来,结合注释有助于更好的理解

网站效果演示:ashuai.work:8888/#/myButton

GitHub仓库地址:github.com/shuirongshu…

什么是Button组件

按钮用于点击,一般是做事件的响应。

按钮封装效果图

按钮分类

  • 单一按钮
    • 默认按钮
    • 主题按钮(primary、success、warning、error)
    • 按钮大小(small、middle、big)
    • 按钮禁用(disabled)
    • 按钮加载(loading)
    • 按钮的图标位置(默认图标在按钮文字左侧)
    • 图标按钮(没有按钮文字)
    • 单一文字按钮
  • 按钮组(按钮组中有多个按钮)

默认按钮

默认按钮很简单,只是写一个最普通的样式即可

<button :class="[ 'myButton' ]" />

.myButton {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  white-space: nowrap;
  box-sizing: border-box;
  padding: 12px 16px;
  background-color: rgba(0, 0, 0, 0.1);
  color: #222;
  border: none;
  cursor: pointer;
  user-select: none; // 不让选中文字
  transition: all 0.3s;
  font-size: 14px;
}
// 悬浮效果
.myButton:hover {
  background-color: rgba(0, 0, 0, 0.2);
}
// 按中效果
.myButton:active {
  background-color: rgba(0, 0, 0, 0.3);
}

笔者这里是将悬浮的效果和按中的效果,设置背景色越来越深。这样的话,看着效果比较明显

主题按钮

所谓按钮的主题,就是添加不同的类名,比如primary主题的按钮,就加上.primary类名、success主题的按钮,就加上.success类名。然后使用动态class去添加即可(这里使用动态class的数组用法)。如:

<button :class="[ 'myButton', type ]" />

变量type的值源自于使用按钮组件时,传递进来的type参数

const typeArr = [
  "",
  "primary",
  "success",
  "warning",
  "error",
  "text",
  "dangerText",
];

props:{
    type: { // 按钮主题类型
      type: String,
      validator(val) {
        return typeArr.includes(val); // 这里可以加一个校验函数,其实不加也行
      },
    },
}

然后给不同type值加上对应的样式即可。如下:

// primary样式
.primary {
  background-color: #1867c0;
  color: #fff;
}
.primary:hover {
  background-color: #0854ac;
}
.primary:active {
  background-color: #033d7f;
}

// success样式
.success {
  background-color: #19be6b;
  color: #fff;
}
.success:hover {
  background-color: #0ea459;
}
.success:active {
  background-color: #008140;
}

// warning样式
.warning {
  background-color: #ffc163;
  color: #fff;
}
.warning:hover {
  background-color: #db952d;
}
.warning:active {
  background-color: #b97b1d;
}

// 等等type值样式...

按钮大小

按钮大小可以使用padding值的大小去控制,也可以直接使用zoom缩放做控制

这里使用动态style搭配计算属性的方式去控制,如下代码:

// 不同的大小指定不同的缩放程度
const sizeObj = {
  small: 0.85,
  middle: 1,
  big: 1.2,
};

props:{ size: String }

<button :style="styleCal" />

computed: {
    styleCal() {
        return {
            zoom: sizeObj[this.size] // zoom缩放的值大小取决于传递进来的size值
        }
    }
}

按钮禁用

按钮禁用disable没啥好说的,主要是要注意loading的时候,也要禁用掉,loading加载的时候,不允许用户再点击。

<button :disabled="disabled || loading" />

props:{
    loading:Boolean
}

这里注意一下,按钮禁用的样式也是通过动态class加上的,请往下看

按钮加载

注意加载时样式和加载按钮图标出来的时候,将其他的图标给隐藏起来。(同一时刻,只能有一个按钮图标,这样保证按钮加载时简洁一些)

  <button
    :class="[
      'myButton', // 默认样式
      disabled ? 'disabledBtn' : '', // 动态加上禁用按钮样式
      loading ? 'loadingBtn' : '', // 动态加上loading加载中按钮样式
      type, // 主题样式
    ]"
    :disabled="disabled || loading" // 禁用时禁用,加载时也禁用
  >
    <i class="el-icon-loading" v-if="loading"></i>
    <!-- 使用传进来的图标,通过动态style控制图标和文字见的间隔,同一时刻下,
    只能有一个图标出现,所以有loading图标了,就不能有别的图标了 -->
    <i :class="icon" :style="styleGap" v-if="icon && !loading"></i>
    <slot></slot>
  </button>

按钮的图标位置

默认从左往右排列(图标在左侧、文字在右侧),这里我们可以使用弹性盒的方向flexDirection属性,来控制从左往右还是从右往左排列

<button :style="styleCal"/>

styleCal() {
  // 控制缩放和指定默认圆角以及设置图标在文字左侧还是右侧
  let styleObj = {
    zoom: sizeObj[this.size],
    borderRadius: "5px",
    flexDirection: this.rightIcon ? "row-reverse" : "row",
  };
  return styleObj;
},

图标按钮和单一文字按钮

这两个也很简单,

  • 图标按钮注意加圆角的时机
  • 单一文字按钮的样式要预留设置一份即可

然后动态控制一下即可

按钮组

按钮组注意事项:

  • 首先将所有的按钮的圆角全部去掉(这样的话,所有的按钮都是方方正正的按钮了)
  • 然后单独给第一个按钮:first-of-type的左上角和左下角的圆角设置一下
  • 然后再给最后一个按钮last-of-type的右上角和右下角的圆角设置一下
  • 最后,按钮组之间需要有间隔,这里使用border-right做分割线
  • 最最后,再把最后一个按钮的右边框去掉即可,如下css代码
// 附上按钮组样式
.myButtonGroup > .myButton {
  border-radius: unset !important; // 给所有的按钮都去掉圆角
  border-right: 1px solid #fff; // 给按钮加上分隔线条
}
// 第一个按钮左侧圆角
.myButtonGroup > .myButton:first-of-type {
  border-top-left-radius: 5px !important; 
  border-bottom-left-radius: 5px !important;
}
// 最后一个按钮的右侧圆角
.myButtonGroup > .myButton:last-of-type {
  border-top-right-radius: 5px !important;
  border-bottom-right-radius: 5px !important;
  border-right: none; // 同时,清除最后一个按钮的右侧边框
}

代码

复制粘贴即可使用,如果道友觉得代码帮忙到了您,欢迎给咱github仓库一个star哈?

myButton组件

<template>
  <button
    :style="styleCal"
    :class="[
      'myButton',
      disabled ? 'disabledBtn' : '',
      loading ? 'loadingBtn' : '',
      type,
    ]"
    :disabled="disabled || loading"
    @click="clickButton"
  >
    <i class="el-icon-loading iii" v-if="loading"></i>
    <!-- 使用传进来的图标,通过动态style控制图标和文字见的间隔,同一时刻下,
    只能有一个图标出现,所以有loading图标了,就不能有别的图标了 -->
    <i :class="icon" :style="styleGap" v-if="icon && !loading"></i>
    <!-- 普通插槽有东西才去渲染 -->
    <span v-if="$slots.default"><slot></slot></span>
  </button>
</template>

<script>
// 类型校验
const typeArr = [
  "",
  "primary",
  "success",
  "warning",
  "error",
  "text",
  "dangerText",
];
const sizeArr = ["", "small", "middle", "big"]; // 大小检验
const sizeObj = {
  // 不同的大小指定不同的缩放程度
  small: 0.85,
  middle: 1,
  big: 1.2,
};
export default {
  name: "myButton",
  props: {
    disabled: Boolean,
    loading: Boolean, // loading时,不可继续点击(继续点击不生效)
    rightIcon: Boolean, // 通过弹性盒的方向控制图标的位置
    type: {
      type: String,
      validator(val) {
        return typeArr.includes(val);
      },
    },
    size: {
      type: String,
      validator(val) {
        return sizeArr.includes(val);
      },
    },
    icon: String,
  },
  computed: {
    styleCal() {
      // 控制缩放和指定默认圆角以及设置图标在文字左侧还是右侧
      let styleObj = {
        zoom: sizeObj[this.size],
        borderRadius: "5px",
        flexDirection: this.rightIcon ? "row-reverse" : "row",
      };
      // 当有图标,且没有文字的时候(或默认插槽没传),就让按钮变成圆形按钮
      if ((this.icon && !this.$slots.default) || !this.$slots.default[0].text) {
        styleObj["borderRadius"] = "50%";
        styleObj["padding"] = "12px";
      }
      return styleObj;
    },
    styleGap() {
      // 有图标,有文字,图标在左侧
      if (
        (this.icon && !this.$slots.default) ||
        (this.$slots.default[0].text && !this.rightIcon)
      ) {
        return {
          paddingRight: "1px",
        };
      }
      // 有图标,有文字,图标在右侧
      if (
        (this.icon && !this.$slots.default) ||
        (this.$slots.default[0].text && this.rightIcon)
      ) {
        return {
          paddingLeft: "1px",
        };
      }
    },
  },
  methods: {
    clickButton(e) {
      if (this.disabled) return;
      this.$emit("click", e); // 传出去,便于使用
    },
  },
};
</script>

<style lang='less' scoped>
/* 关于按钮的样式即写好几套样式,然后通过类型等各种参数去控制样式,最终实现对应效果 */

// 基础样式
.myButton {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  white-space: nowrap;
  box-sizing: border-box;
  padding: 12px 16px;
  background-color: rgba(0, 0, 0, 0.1);
  color: #222;
  border: none;
  cursor: pointer;
  user-select: none;
  transition: all 0.3s;
  font-size: 14px;
  .iii {
    margin-right: 4px;
  }
}
.myButton:hover {
  background-color: rgba(0, 0, 0, 0.2);
}
.myButton:active {
  background-color: rgba(0, 0, 0, 0.3);
}

// primary样式
.primary {
  background-color: #1867c0;
  color: #fff;
}
.primary:hover {
  background-color: #0854ac;
}
.primary:active {
  background-color: #033d7f;
}

// success样式
.success {
  background-color: #19be6b;
  color: #fff;
}
.success:hover {
  background-color: #0ea459;
}
.success:active {
  background-color: #008140;
}

// warning样式
.warning {
  background-color: #ffc163;
  color: #fff;
}
.warning:hover {
  background-color: #db952d;
}
.warning:active {
  background-color: #b97b1d;
}

// error样式
.error {
  background-color: #ff5252;
  color: #fff;
}
.error:hover {
  background-color: #fd3030;
}
.error:active {
  background-color: #d50000;
}

// text样式
.text {
  background-color: unset;
  color: #409eff;
  padding: 2px 4px;
}
.text:hover {
  background-color: unset;
  opacity: 0.9;
}
.text:active {
  background-color: unset;
  opacity: 1;
  color: #1a7ada;
}

// dangerText样式
.dangerText {
  background-color: unset;
  color: #ff5252;
  padding: 2px 4px;
}
.dangerText:hover {
  background-color: unset;
  opacity: 0.9;
}
.dangerText:active {
  background-color: unset;
  opacity: 1;
  color: #d50000;
}

// 加载按钮样式
.loadingBtn {
  opacity: 0.6;
  pointer-events: none; // 值为none就没有hover和active效果了
}

// disabled样式(注意样式的顺序)
.disabledBtn {
  background-color: rgba(0, 0, 0, 0.12);
  color: #bbb;
}
.disabledBtn:hover {
  opacity: 1;
  cursor: not-allowed;
  background-color: rgba(0, 0, 0, 0.12);
}
.disabledBtn:active {
  color: #bbb;
  opacity: 1;
  background-color: rgba(0, 0, 0, 0.12);
}

// 附上按钮组样式
.myButtonGroup > .myButton {
  border-radius: unset !important;
  border-right: 1px solid #fff;
}
.myButtonGroup > .myButton:first-of-type {
  border-top-left-radius: 5px !important;
  border-bottom-left-radius: 5px !important;
}
.myButtonGroup > .myButton:last-of-type {
  border-top-right-radius: 5px !important;
  border-bottom-right-radius: 5px !important;
  border-right: none;
}
</style>

myButtonGroup组件

<template>
  <div class="myButtonGroup">
    <slot></slot>
  </div>
</template>
<script>
export default {
  name: "myButtonGroup",
};
</script>
<style>
.myButtonGroup {
  display: inline-flex !important;
  align-items: center;
}
</style>

使用的时候

<template>
  <div>
    <h5>单个按钮</h5>
    <br />
    <button @click="clickLoad">加载切换</button>
    <div class="btnBox">
      <span class="btn" v-for="(item, index) of btnArr">
        <my-button
          style="margin-right: 16px"
          :key="index"
          :type="item.type"
          :size="item.size"
          :disabled="item.disabled"
          :loading="item.loading"
          :icon="item.icon"
          :rightIcon="item.rightIcon"
          @click="
            (e) => {
              clickBtn(item, e);
            }
          "
          >{{ item.name }}</my-button
        >
      </span>
    </div>
    <br />
    <h5>按钮组</h5>
    <br />
    <my-button-group>
      <my-button type="success" icon="el-icon-arrow-left">上一页</my-button>
      <my-button type="success" icon="el-icon-arrow-right" :rightIcon="true"
        >下一页</my-button
      >
    </my-button-group>
    <br />
    <br />
    <my-button-group>
      <my-button type="primary" icon="el-icon-user"></my-button>
      <my-button type="primary" icon="el-icon-view"></my-button>
      <my-button type="primary" icon="el-icon-star-off"></my-button>
      <my-button type="primary" icon="el-icon-chat-dot-square"></my-button>
      <my-button type="primary" icon="el-icon-share"></my-button>
    </my-button-group>
  </div>
</template>

<script>
export default {
  name: "myButtonName",
  data() {
    return {
      loadingF: false,
      btnArr: [
        {
          type: "",
          name: "默认按钮",
        },
        {
          type: "primary",
          name: "primary",
        },
        {
          type: "success",
          name: "success",
        },
        {
          type: "warning",
          name: "warning",
        },
        {
          type: "error",
          name: "error",
        },
        {
          type: "primary",
          name: "size=small",
          size: "small",
        },
        {
          type: "primary",
          name: "size=middle",
          size: "middle",
        },
        {
          type: "primary",
          name: "size=big",
          size: "big",
        },
        {
          type: "success", // 不管type什么类型,只要禁用全部置灰
          name: "disabled",
          disabled: true,
        },
        {
          type: "primary",
          name: "等待加载",
          loading: false,
        },
        {
          type: "success",
          name: "等待加载",
          loading: false,
        },
        {
          type: "success",
          name: "icon",
          icon: "el-icon-star-on",
        },
        {
          type: "success",
          name: "icon",
          icon: "el-icon-star-on",
          rightIcon: true,
        },
        {
          type: "success",
          name: "",
          icon: "el-icon-edit",
        },
        {
          type: "error",
          name: "",
          icon: "el-icon-delete",
        },
        {
          type: "text",
          name: "纯text按钮",
          // loading: true,
        },
        {
          type: "dangerText",
          name: "dangerText按钮",
          icon: "el-icon-delete-solid",
        },
        {
          type: "text",
          name: "text禁用",
          disabled: true,
        },
      ],
    };
  },
  methods: {
    clickLoad() {
      let lebel = this.btnArr[9].name;
      let newItem9 = {
        type: "primary",
        name: lebel == "等待加载" ? "加载中" : "等待加载",
        loading: lebel == "等待加载" ? true : false,
      };
      this.$set(this.btnArr, 9, newItem9);
      let newItem10 = {
        type: "success",
        name: lebel == "等待加载" ? "加载中" : "等待加载",
        loading: lebel == "等待加载" ? true : false,
      };
      this.$set(this.btnArr, 10, newItem10);
    },
    // 注意这种写法,可接收多个参数
    clickBtn(item, e) {
      console.log("clickBtn", item, e);
    },
  },
};
</script>

<style>
.btnBox {
  width: 100%;
  box-sizing: border-box;
  padding: 24px 0;
  display: flex;
  align-items: flex-end;
  flex-wrap: wrap;
}
.btn {
  margin-bottom: 24px;
}
</style>

本文转载于:

https://juejin.cn/post/7182113902539309112

如果对您有所帮助,欢迎您点个关注,我会定时更新技术文档,大家一起讨论学习,一起进步。

 

有关记录--elementui源码学习之仿写一个el-button的更多相关文章

  1. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  2. ruby-on-rails - Rails - 一个 View 中的多个模型 - 2

    我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何

  3. ruby-on-rails - 渲染另一个 Controller 的 View - 2

    我想要做的是有2个不同的Controller,client和test_client。客户端Controller已经构建,我想创建一个test_clientController,我可以使用它来玩弄客户端的UI并根据需要进行调整。我主要是想绕过我在客户端中内置的验证及其对加载数据的管理Controller的依赖。所以我希望test_clientController加载示例数据集,然后呈现客户端Controller的索引View,以便我可以调整客户端UI。就是这样。我在test_clients索引方法中试过这个:classTestClientdefindexrender:template=>

  4. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  5. ruby - Sinatra:运行 rspec 测试时记录噪音 - 2

    Sinatra新手;我正在运行一些rspec测试,但在日志中收到了一堆不需要的噪音。如何消除日志中过多的噪音?我仔细检查了环境是否设置为:test,这意味着记录器级别应设置为WARN而不是DEBUG。spec_helper:require"./app"require"sinatra"require"rspec"require"rack/test"require"database_cleaner"require"factory_girl"set:environment,:testFactoryGirl.definition_file_paths=%w{./factories./test/

  6. ruby - 为什么 SecureRandom.uuid 创建一个唯一的字符串? - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion为什么SecureRandom.uuid创建一个唯一的字符串?SecureRandom.uuid#=>"35cb4e30-54e1-49f9-b5ce-4134799eb2c0"SecureRandom.uuid方法创建的字符串从不重复?

  7. ruby-on-rails - Rails - 从另一个模型中创建一个模型的实例 - 2

    我有一个正在构建的应用程序,我需要一个模型来创建另一个模型的实例。我希望每辆车都有4个轮胎。汽车模型classCar轮胎模型classTire但是,在make_tires内部有一个错误,如果我为Tire尝试它,则没有用于创建或新建的activerecord方法。当我检查轮胎时,它没有这些方法。我该如何补救?错误是这样的:未定义的方法'create'forActiveRecord::AttributeMethods::Serialization::Tire::Module我测试了两个环境:测试和开发,它们都因相同的错误而失败。 最佳答案

  8. ruby-on-rails - Rails 5 Active Record 记录无效错误 - 2

    我有两个Rails模型,即Invoice和Invoice_details。一个Invoice_details属于Invoice,一个Invoice有多个Invoice_details。我无法使用accepts_nested_attributes_forinInvoice通过Invoice模型保存Invoice_details。我收到以下错误:(0.2ms)BEGIN(0.2ms)ROLLBACKCompleted422UnprocessableEntityin25ms(ActiveRecord:4.0ms)ActiveRecord::RecordInvalid(Validationfa

  9. ruby - 用 Ruby 编写一个简单的网络服务器 - 2

    我想在Ruby中创建一个用于开发目的的极其简单的Web服务器(不,不想使用现成的解决方案)。代码如下:#!/usr/bin/rubyrequire'socket'server=TCPServer.new('127.0.0.1',8080)whileconnection=server.acceptheaders=[]length=0whileline=connection.getsheaders想法是从命令行运行这个脚本,提供另一个脚本,它将在其标准输入上获取请求,并在其标准输出上返回完整的响应。到目前为止一切顺利,但事实证明这真的很脆弱,因为它在第二个请求上中断并出现错误:/usr/b

  10. ruby - 一个 YAML 对象可以引用另一个吗? - 2

    我想让一个yaml对象引用另一个,如下所示:intro:"Hello,dearuser."registration:$introThanksforregistering!new_message:$introYouhaveanewmessage!上面的语法只是它如何工作的一个例子(这也是它在thiscpanmodule中的工作方式。)我正在使用标准的ruby​​yaml解析器。这可能吗? 最佳答案 一些yaml对象确实引用了其他对象:irb>require'yaml'#=>trueirb>str="hello"#=>"hello"ir

随机推荐