Vue3封装Butoon组件

因为在项目中会经常用到按钮,基于vue的组件化开发,我就想封装一个button组件,供全局使用,本文实现的是简单的封装,涉及到更多要求的也可以按照这个模版继续添加

工具:

  1. vue3
  2. svg

如果不想在按钮里加图标,可以用svg或者其他图标框架,总之能实现在按钮里加上图标即可,本文使用的是svg作为icon引入,如果也想使用svg,请看:Vue3+Vite 全局封装Svg图标-CSDN博客

1. 封装

<script lang="ts" setup>
interface Props {
    width?: number, // 按钮宽度
    height?: number, // 按钮高度
    borderRadius?: number, // 按钮圆角
    bg?: string, // 背景颜色
    showIcon?: boolean, // 是否显示icon
    iconName?: string, // icon名称
    text: string, // 按钮文字
}

const props = withDefaults(defineProps<Props>(), {
    width: 100, // 默认宽度100
    height: 35, // 默认高度35
    borderRadius: 20, // 默认圆角度数:20
    showIcon: false, // 默认不显示icon
})
// 直接在js中处理拼接好样式,然后通过vue的样式绑定到按钮上就可以实现按钮样式动态改变了
// 按钮的样式
const btnStyle = {
    width: props.width + 'px',
    height: props.height + 'px',
    borderRadius: props.borderRadius + 'px',
    fontSize: (props.height - 20) + 'px',
}
// 图标样式
const iconStyle = {
    width: (props.height - 15) + 'px',
    height: (props.height - 15) + 'px',
}
</script>

<template>
    <div class="btn-container">
        <button :style="btnStyle">
            <svg v-if="showIcon" class="icon" :style="iconStyle">
                <use :xlink:href="`#icon-${iconName}`"/>
            </svg>
            {{ text }}
        </button>
    </div>
</template>

<style lang="scss" scoped>
.btn-container {
  button {
    border: 1px solid #eee;
    background-color: #fff;
    color: #000;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;

    .icon {
      margin-right: 5px;
    }
  }

  button:hover {
    cursor: pointer;
  }
}
</style>

2. 使用

<MyButton :text="'按钮'" :iconName="'location'" :show-icon="true"/>

3. 效果

  • 10
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值