element-ui 二次封装系列- button(三)

3,372 阅读2分钟

前两篇对el-button分别扩充了两个功能,一个自动loading,一个自动confirm,本文继续对el-button进行扩充功能 很多时候 ,我们希望按钮能有一个 tooltip的功能,鼠标放在按钮上能够展示一些解释性的文字,el-tooltip组件正是实现这个功能的,但是直接用el-tooltip组件代码非常多,需要将el-button作为slot插入内容,如果能直接给button上添加content自动展示那就非常简洁了. 带tooltip的button 这里我们在前面的pl-button基础上再次包裹封装一个pl-tip-button组件,

<template>
  <el-tooltip :content="content" v-bind="attrs">
    <pl-button v-bind="$attrs" v-on="$listeners">
      <slot />
    </pl-button>
  </el-tooltip>
</template>

<script>
export default {
  name: 'PlTipButton',
  props: {
    content: {
      type: String,
      required: true
    },
    tipConfig: {
      type: Object,
      default: null
    }
  },
  computed: {
    attrs() {
      return {
        effect: 'dark',
        placement: 'top',
        ...this.tipConfig
      }
    }
  }
}
</script>

以上简单的几句代码,我们将el-tooltipel-button结合起来了,这里为了继承事件和属性,采用了 v-bind=$attrs, v-on=$listeners,同时,对于一次绑定多个属性,我们采用v-bind=attrs这样绑定对象的方式,注意,这里的attrs没有加$,这是我们采用计算属性合成的一个对象,用来合并el-tooltip的属性. 来看看怎么使用吧

  <pl-tip-button content="设置" icon="el-icon-s-tools" circle>
  </pl-tip-button>
   <pl-tip-button
      content="删除"
      type="primary"
      auto-confirm
      @confirm="confirm"
      :tip-config={effect:"light",placement:"bottom"}
    >删除
    </pl-tip-button>
     <pl-tip-button
      content="删除"
      type="primary"
      auto-loading
     @click="handleClick"
    >删除
    </pl-tip-button>

这里我们可以合并前面两篇文章中扩展的 自动loading自动confirm功能,还能使用el-button的原有功能如示例代码中的typeicon,circle等属性,同时,如果我们想设置el-tooltip的一些属性,我们可以传入tipConfigprops,这里面可以是所有的el-tooltopprops属性的对象.

限于掘金不能方便的展示,你可以通过查看此文档查看效果www.noob6.com/pl-element/…

源码地址

系列文章地址:

element-ui 二次封装系列- button(一)

element-ui 二次封装系列- button(二)

element-ui 二次封装系列- button(三)

element-ui 二次封装系列- button(四)(vue3版本)