vue 实现toast
实现 Vue Toast 的几种方法
使用第三方库(推荐)
vue-toastification 是一个流行的 Vue Toast 库,安装简单且功能丰富。
安装:
npm install vue-toastification@next
在 main.js 中引入:
import Toast from "vue-toastification"
import "vue-toastification/dist/index.css"
const app = createApp(App)
app.use(Toast)
使用示例:
this.$toast("Hello world!")
this.$toast.success("Success!")
this.$toast.error("Error occurred")
自定义组件实现
创建一个 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 = 3000) {
this.message = message
this.show = true
setTimeout(() => {
this.show = false
}, duration)
}
}
}
</script>
<style>
.toast {
position: fixed;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
padding: 12px 24px;
background: rgba(0,0,0,0.7);
color: white;
border-radius: 4px;
z-index: 9999;
}
</style>
在 main.js 中全局注册:
import Toast from '@/components/Toast'
const app = createApp(App)
app.component('Toast', Toast)
使用方式:
this.$refs.toast.display('Hello world')
使用 Vue 插件方式
创建 toast.js 插件:

export default {
install(app) {
app.config.globalProperties.$toast = {
show(message, duration = 3000) {
const toast = document.createElement('div')
toast.className = 'toast-message'
toast.textContent = message
document.body.appendChild(toast)
setTimeout(() => {
document.body.removeChild(toast)
}, duration)
}
}
}
}
在 main.js 中引入:
import toast from './plugins/toast'
const app = createApp(App)
app.use(toast)
使用方式:
this.$toast.show('This is a toast message')
样式补充
对于自定义实现,添加 CSS:
.toast-message {
position: fixed;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
padding: 12px 24px;
background: rgba(0,0,0,0.8);
color: white;
border-radius: 4px;
z-index: 9999;
animation: fadeIn 0.3s, fadeOut 0.3s 2.7s;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes fadeOut {
from { opacity: 1; }
to { opacity: 0; }
}
每种方法各有优劣,第三方库功能最全但增加包体积,自定义实现更轻量但需要自行处理更多细节。根据项目需求选择合适方案。






