vue实现按钮
Vue 实现按钮的基本方法
在 Vue 中实现按钮可以通过原生 HTML 的 <button> 标签或使用 Vue 的组件化特性封装自定义按钮组件。以下是两种常见实现方式:
使用原生 HTML 按钮
<template>
<button @click="handleClick">点击按钮</button>
</template>
<script>
export default {
methods: {
handleClick() {
console.log('按钮被点击');
}
}
}
</script>
封装可复用的按钮组件
<!-- Button.vue -->
<template>
<button
:class="['custom-button', type]"
:disabled="disabled"
@click="$emit('click')"
>
<slot></slot>
</button>
</template>
<script>
export default {
props: {
type: {
type: String,
default: 'default' // 支持 primary/danger 等样式类型
},
disabled: Boolean
}
}
</script>
<style scoped>
.custom-button {
padding: 8px 16px;
border-radius: 4px;
}
.primary {
background-color: blue;
color: white;
}
</style>
按钮功能扩展
添加加载状态
<template>
<button :disabled="loading">
<span v-if="loading">加载中...</span>
<span v-else><slot></slot></span>
</button>
</template>
<script>
export default {
props: {
loading: Boolean
}
}
</script>
防抖处理
import { debounce } from 'lodash';
methods: {
handleClick: debounce(function() {
// 防抖逻辑
}, 300)
}
第三方 UI 库的按钮
Element UI 按钮
<el-button type="primary" @click="submit">提交</el-button>
Ant Design Vue 按钮
<a-button type="primary" @click="handleClick">确定</a-button>
按钮无障碍访问
遵循 WAI-ARIA 标准实现无障碍按钮:
<button
aria-label="关闭对话框"
aria-disabled="false"
tabindex="0"
>
关闭
</button>
按钮样式方案
CSS Modules
<button :class="$style.button">样式按钮</button>
<style module>
.button {
background: var(--primary-color);
}
</style>
Tailwind CSS
<button class="px-4 py-2 bg-blue-500 text-white rounded">
Tailwind 按钮
</button>






