vue公共按钮实现
Vue 公共按钮组件的实现方法
封装基础按钮组件
创建一个可复用的基础按钮组件,通常放在 src/components 目录下。示例代码:
<template>
<button
:class="['base-button', type, size, { 'disabled': disabled }]"
:disabled="disabled"
@click="handleClick"
>
<slot></slot>
</button>
</template>
<script>
export default {
name: 'BaseButton',
props: {
type: {
type: String,
default: 'default',
validator: value => ['default', 'primary', 'danger', 'warning'].includes(value)
},
size: {
type: String,
default: 'medium',
validator: value => ['small', 'medium', 'large'].includes(value)
},
disabled: {
type: Boolean,
default: false
}
},
methods: {
handleClick(e) {
this.$emit('click', e)
}
}
}
</script>
<style scoped>
.base-button {
border-radius: 4px;
cursor: pointer;
transition: all 0.3s;
}
.primary {
background-color: #1890ff;
color: white;
}
.danger {
background-color: #ff4d4f;
color: white;
}
.small {
padding: 4px 8px;
font-size: 12px;
}
.large {
padding: 10px 16px;
font-size: 16px;
}
.disabled {
opacity: 0.6;
cursor: not-allowed;
}
</style>
全局注册组件
在 main.js 中全局注册组件,方便在整个项目中使用:
import Vue from 'vue'
import BaseButton from '@/components/BaseButton.vue'
Vue.component('BaseButton', BaseButton)
使用动态插槽和图标
增强按钮组件的灵活性,支持图标和动态内容:
<template>
<button class="base-button" :class="[type, size]">
<span v-if="$slots.icon" class="icon-wrapper">
<slot name="icon"></slot>
</span>
<slot></slot>
</button>
</template>
<style scoped>
.icon-wrapper {
display: inline-flex;
align-items: center;
margin-right: 4px;
}
</style>
实现按钮权限控制
结合项目权限系统,添加权限验证功能:
<script>
export default {
props: {
permission: {
type: String,
default: ''
}
},
computed: {
hasPermission() {
return !this.permission || this.$store.getters.hasPermission(this.permission)
}
}
}
</script>
<template>
<button v-if="hasPermission" class="base-button">
<slot></slot>
</button>
</template>
集成Loading状态
添加异步操作时的Loading状态反馈:
<template>
<button
class="base-button"
:disabled="loading"
>
<span v-if="loading" class="loading-spinner"></span>
<slot v-else></slot>
</button>
</template>
<script>
export default {
props: {
loading: {
type: Boolean,
default: false
}
}
}
</script>
<style scoped>
.loading-spinner {
display: inline-block;
width: 14px;
height: 14px;
border: 2px solid rgba(255,255,255,0.3);
border-radius: 50%;
border-top-color: white;
animation: spin 1s ease-in-out infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
</style>
主题定制方案
通过CSS变量实现主题定制:

<style scoped>
.base-button {
--primary-color: #1890ff;
--danger-color: #ff4d4f;
--warning-color: #faad14;
}
.primary {
background-color: var(--primary-color);
}
.danger {
background-color: var(--danger-color);
}
.warning {
background-color: var(--warning-color);
}
</style>






