vue徽章效果实现
Vue 徽章效果实现方法
使用 CSS 和 Vue 动态绑定
通过 Vue 的动态绑定和 CSS 样式实现徽章效果。在模板中使用 v-if 或 v-show 控制徽章显示,结合计算属性动态计算徽章内容。
<template>
<div class="badge-container">
<span class="badge" v-if="badgeCount > 0">{{ badgeCount }}</span>
</div>
</template>
<script>
export default {
data() {
return {
badgeCount: 5
}
}
}
</script>
<style>
.badge {
position: absolute;
top: -5px;
right: -5px;
background-color: red;
color: white;
border-radius: 50%;
width: 20px;
height: 20px;
display: flex;
align-items: center;
justify-content: center;
font-size: 12px;
}
.badge-container {
position: relative;
display: inline-block;
}
</style>
使用第三方组件库
多数流行的 Vue UI 组件库提供现成的徽章组件,例如 Element UI、Vuetify 或 Ant Design Vue。
Element UI 示例:

<template>
<el-badge :value="12" class="item">
<el-button>消息</el-button>
</el-badge>
</template>
Vuetify 示例:
<template>
<v-badge content="6" color="error">
<v-icon>mdi-bell</v-icon>
</v-badge>
</template>
自定义徽章组件
创建可复用的徽章组件,支持更多自定义选项如颜色、位置、形状等。

<template>
<Badge :count="unreadCount" :max="99" type="primary" />
</template>
<script>
import Badge from './Badge.vue'
export default {
components: { Badge },
data() {
return {
unreadCount: 25
}
}
}
</script>
动画效果增强
为徽章添加出现/消失的动画效果,提升用户体验。
.badge {
transition: all 0.3s ease;
transform: scale(1);
}
.badge-enter-active, .badge-leave-active {
transition: all 0.3s;
}
.badge-enter, .badge-leave-to {
transform: scale(0);
}
服务端数据绑定
结合 Vuex 或 API 调用实现动态徽章数据更新。
computed: {
badgeCount() {
return this.$store.state.notificationCount
}
},
created() {
this.$store.dispatch('fetchNotifications')
}






