手动封装element-ui里面的button组件

本文介绍如何在Vue中手动封装一个具有Element-UI风格的Button组件。从创建组件开始,逐步讲解如何利用插槽添加自定义文字,通过props传递type属性控制按钮样式,动态绑定样式以实现plain和round属性,引入字体图标,并处理点击事件及禁用状态。通过这个过程,完整地展示了Element-UI Button组件的封装步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先我们知道vue里面包含有父子组件

但是你知道如果要进行一个element的手动组件封装

怎么封装吗

1首先第一步

首先我们建立一个组件

最好设置在一个文件目录下比如components

只是一个普通的组件

叫做OneButton.vue

    <template>
      <button class="one-button">
       按钮组件
      </button>
    </template>
     
    <script>
     
    export default {
      name: 'oneButton'
    }
</script>
     
    <style lang="scss">
</style>

要想使用该组件

就需要进行全局注册

就是在main.js里面注册了

 import Vue from 'vue'
    import App from './App.vue'
    // 第一步:导入button组件
    import OneButton from './components/button.vue'
     
    Vue.config.productionTip = false
     
    // 第二步:注册组件,设置(组件名,组件)
    Vue.component(OneButton.name, OneButton)
     
    new Vue({
      render: h => h(App)
    }).$mount('#app')

注册完成以后就可以进行使用了

<template>
  <div id="app">
    <one-button>按钮</one-button>

  </div>
</template>

<script>
export default {
  name: 'App',
  components: {}
}
</script>

<style lang="scss">
</style>

到这里

我们可以看到 就会显示一个普通按钮了

但是吧 这样的封装过于简单

能不能实现更加复杂的操作呢

于是

我们需要封装一个有element-ui风格的组件

好 那我们继续实现

我们先让文字可以自由的输入

那就要利用插槽了

 <template>
      <button class="one-button">
       <span><slot></slot></span>
      </button>
    </template>

我们的文件需要做以上处理

 <template>
      <div>
        <one-button>歌谣</one-button>
        <one-button>帅气</one-button>
        <one-button>关注我</one-button>
      </div>
    </template>

加上基本样式

 <style lang="scss">
      .one-button{
        display: inline-block;
        line-height: 1;
        white-space: nowrap;
        cursor: pointer;
        background: #ffffff;
        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;
        -moz-user-select: none;
        -ms-user-select: none;
        padding: 12px 20px;
        font-size: 14px;
        border-radius: 4px;
        &:hover,
        &:hover{
          color: #409eff;
          border-color: #c6e2ff;
          background-color: #ecf5ff;
        }
      }
    </style>

这样文字的效果就实现了

到了这里 你又想element里面可以控制type属性控制按钮样式

怎么可以实现呢

父元素传递type值

    <template>
      <div id="app">
        <div class="row">
        <one-button>按钮</one-button>
        <one-button type="primary">primary按钮
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端小歌谣

放弃很容易 但是坚持一定很酷

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值