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