# m-button
# 介绍
m-button
组件,结构与样式使用 el-button
组件,之后根据项目按钮使用情况,做了一些参数分类,使用上更加便捷。
# 目录结构
└─ src
└─ components
└─ MButton # 按钮组件
# 源码
<template>
<button
class="el-button"
@click="handleClick"
:disabled="disabled || loading"
:autofocus="autofocus"
:type="nativeType"
:class="[
buttonType ? 'el-button--' + buttonType : '',
buttonSize ? 'el-button--' + buttonSize : '',
{
'is-disabled': disabled,
'is-loading': loading,
'is-plain': plain,
'is-round': round,
'is-circle': circle,
},
]"
>
<!-- 加载动画 -->
<i class="el-icon-loading" v-if="loading"></i>
<!-- 图标,如果加载中则显示加载动画 -->
<i :class="butttonIcon" v-if="butttonIcon && !loading"></i>
<!-- 按钮自定义内容 -->
<span v-if="$slots.default"><slot></slot></span>
<!-- 按钮文字内容 -->
<span v-else-if="buttonText">{{ buttonText }}</span>
</button>
</template>
export default {
name: "MButton",
props: {
type: {
type: String,
default: "default",
},
size: {
type: String,
},
icon: {
type: String,
default: "",
},
nativeType: {
type: String,
default: "button",
},
to: [String, Object],
replace: Boolean,
loading: Boolean,
disabled: Boolean,
plain: Boolean,
autofocus: Boolean,
round: Boolean,
circle: Boolean,
},
computed: {
// 按钮类型,根据类型不同显示不同颜色
buttonType() {
let btnType = this.type;
switch (btnType) {
case "cancel":
btnType = "";
break;
case "detail":
case "search":
case "submit":
btnType = "primary";
break;
case "sort":
case "set":
case "edit":
case "status":
btnType = "warning";
break;
case "delete":
btnType = "danger";
break;
case "create":
case "refresh":
btnType = "success";
break;
}
return btnType;
},
// 按钮尺寸,根据不行类型显示不同尺寸
_typeSize() {
let btnSize = "";
switch (this.type) {
case "create":
case "search":
case "refresh":
case "sort":
btnSize = "medium";
break;
default:
btnSize = "small";
}
return btnSize;
},
// 按钮尺寸,如果有传入尺寸,则使用传入值
// 否则根据传入类型设置不同尺寸
buttonSize() {
return this.size || this._typeSize;
},
// 按钮图标,根据不同类型设置不同图标
_typeIcon() {
let btnIcon = "";
switch (this.type) {
case "create":
btnIcon = "el-icon-plus";
break;
case "search":
btnIcon = "el-icon-search";
break;
case "refresh":
btnIcon = "el-icon-refresh";
break;
case "sort":
btnIcon = "el-icon-sort";
break;
default:
btnIcon = this.icon;
}
return btnIcon;
},
// 如果传入了图标,则使用传入值
butttonIcon() {
return this.icon || this._typeIcon;
},
// 按钮内容,如果未传入值,则根据传入类型设置默认值
buttonText() {
if (this.$slots.default) return;
let btnText = "";
switch (this.type) {
case "detail":
btnText = "详情";
break;
case "edit":
btnText = "编辑";
break;
case "set":
btnText = "设置";
break;
case "status":
btnText = "状态";
break;
case "delete":
btnText = "删除";
break;
case "cancel":
btnText = "取 消";
break;
case "submit":
btnText = "保 存";
break;
case "create":
btnText = "添 加";
break;
case "search":
btnText = "搜 索";
break;
case "sort":
btnText = "排 序";
break;
}
return btnText;
},
},
methods: {
// 按钮click事件
handleClick(event) {
// 点击路由跳转
if (this.to) {
if (this.replace) {
this.$router.replace(this.to);
} else {
this.$router.push(this.to);
}
}
// 抛出 click 事件,否则父级 click 需要加上 .native 才会触发
this.$emit("click", event);
},
},
};