vue badge 实现方法
使用组件库实现 Badge
Vue 生态中主流组件库(如 Element UI、Ant Design Vue、Vuetify 等)均提供现成的 Badge 组件。
以 Element UI 为例:
<el-badge :value="12" class="item">
<el-button>评论</el-button>
</el-badge>
Ant Design Vue 示例:

<a-badge count=5>
<a-avatar shape="square"/>
</a-badge>
自定义 Badge 组件
通过 CSS 绝对定位实现基础样式:
<template>
<div class="badge-container">
<slot></slot>
<span class="badge" v-if="count">{{ count }}</span>
</div>
</template>
<script>
export default {
props: ['count']
}
</script>
<style>
.badge-container {
position: relative;
display: inline-block;
}
.badge {
position: absolute;
top: -8px;
right: -8px;
background: red;
color: white;
border-radius: 50%;
width: 16px;
height: 16px;
font-size: 12px;
text-align: center;
line-height: 16px;
}
</style>
动态 Badge 样式
根据数值变化调整样式:

computed: {
badgeClass() {
return {
'badge': true,
'badge-danger': this.count > 10,
'badge-warning': this.count <= 10
}
}
}
动画效果实现
使用 Vue 过渡动画:
<transition name="bounce">
<span class="badge" v-if="show">{{ count }}</span>
</transition>
<style>
.bounce-enter-active {
animation: bounce-in 0.5s;
}
@keyframes bounce-in {
0% { transform: scale(0) }
50% { transform: scale(1.5) }
100% { transform: scale(1) }
}
</style>
服务端数据绑定
结合 Vuex 或 API 数据:
data() {
return {
notificationCount: 0
}
},
mounted() {
fetch('/api/notifications/count')
.then(res => res.json())
.then(data => {
this.notificationCount = data.count
})
}






