说明:v-snackbar 组件适用于统一管理消息提示框(操作反馈的提示)
看效果:
1、在状态管理中创建文件,统一管理
// stores/snackbar.js
/**
* 统一管理消息提示框(操作反馈的提示)
*/
import { defineStore } from 'pinia';
// 消息类型
export const typeColors = {
success: 'success', // 成功
error: 'error', // 错误
warning: 'warning', // 警告
info: 'info', // 默认
default: 'grey-darken-1'
};
export const useSnackbar = defineStore('snackbar', {
state: () => ({
show: false,
text: '',
color: typeColors.default,
timeout: 3000,
icon: '',
closable: false
}),
actions: {
/**
* 显示提示信息
* @param {string} message - 提示内容
* @param {string} type - 类型 success | error | warning | info | default
* @param {Object} options - 可选配置项
* @param {boolean} options.closable - 是否显示关闭按钮
* @param {number} options.timeout - 自动关闭时间(毫秒)
*/
showMessage(message, type = 'default', options = {}) {
const icons = {
success: 'mdi-check-circle',
error: 'mdi-alert-circle',
warning: 'mdi-alert',
info: 'mdi-information',
default: 'mdi-bell-outline'
};
this.text = message;
this.color = typeColors[type] || typeColors.default;
this.icon = icons[type] || icons.default;
this.closable = options.closable || false;
this.timeout = this.closable ? -1 : (options.timeout || 3000); // 有关闭按钮不自动关闭
this.show = true;
},
hideMessage() {
this.show = false;
}
}
});
总结:为什么用 stores/snackbar.js
目的 | 说明 |
✅ 全局状态共享 | 任何组件都可以调用,不需要 props 传递 |
✅ 逻辑集中统一 | 所有 Snackbar 显示逻辑都放在一个地方 |
✅ 更易扩展维护 | 未来加 loading、图标、队列等都更容易 |
✅ 简化组件 | AppSnackbar 只关注展示 UI,不管逻辑 |
2、组件封装
<!-- src/components/AppSnackbar.vue -->
<!-- 消息提示组件(操作反馈) -->
<template>
<v-snackbar v-model="snackbar.show" :timeout="snackbar.timeout" :color="snackbar.color" location="top" elevation="6"
rounded="lg" class="text-white">
<template #default>
<v-icon start size="20">{{ snackbar.icon }}</v-icon>
{{ snackbar.text }}
</template>
<!-- 可选的关闭按钮 -->
<template v-if="snackbar.closable" #actions>
<v-btn icon variant="text" @click="snackbar.hideMessage">
<v-icon>mdi-close</v-icon>
</v-btn>
</template>
</v-snackbar>
</template>
<script setup>
import { useSnackbar } from '@/stores/snackbar';
const snackbar = useSnackbar();
</script>
3、 App.vue 中挂载(一次性全局引入)
<template>
<VApp>
<RouterView />
<AppSnackbar />
</VApp>
</template>
<script setup>
import AppSnackbar from '@/components/AppSnackbar.vue'
</script>
4、页面中使用
<template>
<VCard></VCard>
</template>
<script setup>
import { useSnackbar } from '@/stores/snackbar';
const snackbar = useSnackbar();
snackbar.showMessage('保存成功', 'success');
</script>
5、使用示例
自动关闭 + 图标(默认 3 秒)
snackbar.showMessage('保存成功', 'success');
显示 5 秒后自动关闭
snackbar.showMessage('保存失败,请重试', 'error', 5000);
显示关闭按钮 + 不自动关闭
snackbar.showMessage('请手动关闭此提示', 'warning', { closable: true });
效果说明:
参数示例 | 自动关闭 | 关闭按钮 | 图标 |
showMessage('成功', 'success') | ✅ 3秒 | ❌ | ✅ |
showMessage('失败', 'error', { closable: true }) | ❌ | ✅ | ✅ |
showMessage('警告', 'warning', { timeout: 5000 }) | ✅ 5秒 | ❌ | ✅ |
注:Vuetify框架使用会持续更新更多功能使用方法
至此完成!!!
测试有效!!!感谢支持!!!