vue 实现toast组件
实现 Vue Toast 组件
Toast 组件通常用于显示短暂的提示信息,以下是一种常见的实现方式。
创建 Toast 组件文件
创建一个 Toast.vue 文件,包含基本的模板和样式:
<template>
<transition name="fade">
<div v-if="visible" class="toast" :class="type">
{{ message }}
</div>
</transition>
</template>
<script>
export default {
data() {
return {
visible: false,
message: '',
type: 'info' // 可以是 'info', 'success', 'error', 'warning'
}
},
methods: {
show(message, type = 'info', duration = 3000) {
this.message = message
this.type = type
this.visible = true
setTimeout(() => {
this.visible = false
}, duration)
}
}
}
</script>
<style scoped>
.toast {
position: fixed;
top: 20px;
left: 50%;
transform: translateX(-50%);
padding: 12px 24px;
border-radius: 4px;
color: white;
z-index: 9999;
}
.info {
background-color: #1890ff;
}
.success {
background-color: #52c41a;
}
.error {
background-color: #f5222d;
}
.warning {
background-color: #faad14;
}
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
创建插件形式使用
为了使 Toast 可以在任何组件中调用,可以创建一个插件:
// toast-plugin.js
import Vue from 'vue'
import Toast from './Toast.vue'
const ToastPlugin = {
install(Vue) {
const ToastConstructor = Vue.extend(Toast)
const toastInstance = new ToastConstructor()
toastInstance.$mount(document.createElement('div'))
document.body.appendChild(toastInstance.$el)
Vue.prototype.$toast = {
info(message, duration) {
toastInstance.show(message, 'info', duration)
},
success(message, duration) {
toastInstance.show(message, 'success', duration)
},
error(message, duration) {
toastInstance.show(message, 'error', duration)
},
warning(message, duration) {
toastInstance.show(message, 'warning', duration)
}
}
}
}
Vue.use(ToastPlugin)
在 main.js 中引入
import './toast-plugin'
在组件中使用
// 在任何 Vue 组件中
this.$toast.info('这是一条信息提示')
this.$toast.success('操作成功', 2000)
this.$toast.error('发生错误', 5000)
this.$toast.warning('警告信息')
可配置选项扩展
如果需要更多配置选项,可以修改插件代码:
// 修改 toast-plugin.js
Vue.prototype.$toast = {
show(options) {
if (typeof options === 'string') {
options = { message: options }
}
toastInstance.show(
options.message,
options.type || 'info',
options.duration || 3000
)
},
// 保留原来的快捷方法
info(message, duration) {
this.show({ message, type: 'info', duration })
},
// 其他快捷方法...
}
这样实现的 Toast 组件具有以下特点:

- 支持多种消息类型(info、success、error、warning)
- 自动消失,可配置显示时长
- 淡入淡出动画效果
- 全局调用,使用方便
- 响应式位置居中显示






