用vue封装一个按钮的组件,功能多一点
时间: 2024-05-03 21:23:05 浏览: 17
以下是一个具有多种功能的简单Vue按钮组件示例:
```html
<template>
<button class="btn" :class="[type, size, { disabled: isDisabled }]" :disabled="isDisabled" @click="handleClick">
<slot></slot>
<div v-if="isLoading" class="spinner"></div>
</button>
</template>
<script>
export default {
name: 'Button',
props: {
type: {
type: String,
default: 'default',
validator: (value) => ['default', 'primary', 'success', 'warning', 'danger', 'link'].includes(value),
},
size: {
type: String,
default: 'medium',
validator: (value) => ['small', 'medium', 'large'].includes(value),
},
disabled: {
type: Boolean,
default: false,
},
loading: {
type: Boolean,
default: false,
},
},
computed: {
isDisabled() {
return this.disabled || this.isLoading;
},
},
methods: {
handleClick() {
this.$emit('click');
},
},
};
</script>
<style>
.btn {
display: inline-block;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
font-weight: 500;
line-height: 1.5;
padding: 10px 20px;
text-align: center;
text-decoration: none;
transition: background-color 0.3s ease;
}
.btn.default {
color: #333;
background-color: #fff;
border: 1px solid #ccc;
}
.btn.default:hover {
background-color: #f5f5f5;
}
.btn.primary {
color: #fff;
background-color: #007bff;
}
.btn.primary:hover {
background-color: #0069d9;
}
.btn.success {
color: #fff;
background-color: #28a745;
}
.btn.success:hover {
background-color: #218838;
}
.btn.warning {
color: #fff;
background-color: #ffc107;
}
.btn.warning:hover {
background-color: #e0a800;
}
.btn.danger {
color: #fff;
background-color: #dc3545;
}
.btn.danger:hover {
background-color: #c82333;
}
.btn.link {
color: #007bff;
background-color: transparent;
border: none;
}
.btn.link:hover {
background-color: #f5f5f5;
}
.btn.small {
font-size: 12px;
padding: 8px 16px;
}
.btn.medium {
font-size: 14px;
padding: 10px 20px;
}
.btn.large {
font-size: 16px;
padding: 12px 24px;
}
.btn.disabled,
.btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.spinner {
display: inline-block;
width: 12px;
height: 12px;
border: 2px solid #fff;
border-top-color: #007bff;
border-radius: 50%;
animation: spinner 0.75s ease-in-out infinite;
margin-left: 8px;
}
@keyframes spinner {
to {
transform: rotate(360deg);
}
}
</style>
```
这个按钮组件具有以下功能:
- 可以设置按钮的类型,包括:默认(default)、主要(primary)、成功(success)、警告(warning)、危险(danger)和链接(link);
- 可以设置按钮的大小,包括:小(small)、中(medium)和大(large);
- 可以设置按钮是否禁用;
- 可以设置按钮是否处于加载状态,此时将显示一个旋转动画;
- 可以在按钮组件中插入任何内容,包括文字、图标等。