vue实现 toast
Vue 实现 Toast 组件
Toast 是一种轻量级的反馈提示,常用于显示操作结果或简短消息。以下是实现 Vue Toast 组件的几种方法:
使用第三方库
Vue 生态中有许多成熟的 Toast 库,例如 vue-toastification 或 vant 的 Toast 组件,安装后可直接使用:
npm install vue-toastification
在 main.js 中引入并注册:
import Toast from 'vue-toastification'
import 'vue-toastification/dist/index.css'
const app = createApp(App)
app.use(Toast)
在组件中使用:

this.$toast.success("操作成功")
this.$toast.error("操作失败")
自定义全局 Toast 组件
创建一个可复用的全局 Toast 组件:
- 创建 Toast.vue 组件文件:
<template>
<div v-if="show" class="toast">
{{ message }}
</div>
</template>
<script>
export default {
data() {
return {
show: false,
message: ''
}
},
methods: {
display(message, duration = 2000) {
this.message = message
this.show = true
setTimeout(() => {
this.show = false
}, duration)
}
}
}
</script>
<style>
.toast {
position: fixed;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
padding: 10px 20px;
background: rgba(0, 0, 0, 0.7);
color: white;
border-radius: 4px;
z-index: 9999;
}
</style>
- 在 main.js 中注册为全局组件:
import Toast from '@/components/Toast.vue'
const app = createApp(App)
app.component('Toast', Toast)
- 在组件中使用:
this.$refs.toast.display('提示信息')
使用 Vue 插件方式
创建更灵活的 Toast 插件:

- 创建 toast-plugin.js:
const ToastPlugin = {
install(app, options) {
app.config.globalProperties.$toast = {
show(message, duration = 2000) {
const toastEl = document.createElement('div')
toastEl.className = 'vue-toast'
toastEl.textContent = message
document.body.appendChild(toastEl)
setTimeout(() => {
document.body.removeChild(toastEl)
}, duration)
}
}
}
}
export default ToastPlugin
- 在 main.js 中使用:
import ToastPlugin from './toast-plugin'
const app = createApp(App)
app.use(ToastPlugin)
- 在任何组件中调用:
this.$toast.show('提示信息')
添加动画效果
为 Toast 添加淡入淡出动画:
.toast {
/* 其他样式 */
animation: fadeInOut 2s ease-in-out;
}
@keyframes fadeInOut {
0% { opacity: 0; }
10% { opacity: 1; }
90% { opacity: 1; }
100% { opacity: 0; }
}
支持多种类型
扩展 Toast 支持 success/warning/error 等不同类型:
methods: {
show(type, message, duration = 2000) {
const toastEl = document.createElement('div')
toastEl.className = `vue-toast toast-${type}`
toastEl.textContent = message
document.body.appendChild(toastEl)
setTimeout(() => {
document.body.removeChild(toastEl)
}, duration)
}
}
调用方式:
this.$toast.show('success', '操作成功')
this.$toast.show('error', '操作失败')






