vue toast实现
Vue Toast 实现方法
使用第三方库(推荐)
Vue 生态中有许多成熟的 Toast 组件库,例如 vue-toastification 或 vant 的 Toast 组件。以 vue-toastification 为例:
安装依赖:
npm install vue-toastification@2
在 main.js 中引入并配置:
import Toast from 'vue-toastification'
import 'vue-toastification/dist/index.css'
const options = {
timeout: 2000,
position: 'top-right'
}
app.use(Toast, options)
在组件中使用:
this.$toast.success('操作成功')
this.$toast.error('操作失败')
this.$toast.info('提示信息')
自定义 Toast 组件
如果需要完全自定义 Toast,可以手动实现:
创建 Toast.vue 组件:
<template>
<div v-if="show" class="toast">
{{ message }}
</div>
</template>
<script>
export default {
data() {
return {
show: false,
message: ''
}
},
methods: {
showToast(msg, duration = 2000) {
this.message = msg
this.show = true
setTimeout(() => {
this.show = false
}, duration)
}
}
}
</script>
<style>
.toast {
position: fixed;
top: 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>
在全局注册:
import Toast from './components/Toast.vue'
const toast = {
install(Vue) {
const ToastClass = Vue.extend(Toast)
const instance = new ToastClass()
document.body.appendChild(instance.$mount().$el)
Vue.prototype.$toast = instance
}
}
app.use(toast)
使用方式:
this.$toast.showToast('自定义提示')
动画效果增强
为 Toast 添加过渡动画,修改 Toast.vue:
<template>
<transition name="fade">
<div v-if="show" class="toast">
{{ message }}
</div>
</transition>
</template>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
多 Toast 队列处理
当需要同时显示多个 Toast 时,可以改为数组存储:
data() {
return {
toasts: []
}
},
methods: {
showToast(msg, duration = 2000) {
const toast = { id: Date.now(), msg }
this.toasts.push(toast)
setTimeout(() => {
this.toasts = this.toasts.filter(t => t.id !== toast.id)
}, duration)
}
}
模板部分调整为:
<template>
<div class="toast-container">
<transition-group name="fade">
<div v-for="toast in toasts" :key="toast.id" class="toast">
{{ toast.msg }}
</div>
</transition-group>
</div>
</template>






