vue实现toast
Vue 实现 Toast 的方法
使用第三方库(推荐)
安装 vue-toastification 或其他流行库:
npm install vue-toastification
在 main.js 中引入并配置:
import Toast from 'vue-toastification'
import 'vue-toastification/dist/index.css'
const options = {
timeout: 3000,
position: 'top-right'
}
Vue.use(Toast, options)
在组件中使用:
this.$toast.success('操作成功')
this.$toast.error('发生错误')
this.$toast.info('提示信息')
手动实现基础 Toast
创建 Toast.vue 组件:
<template>
<div v-if="show" class="toast" :class="type">
{{ message }}
</div>
</template>
<script>
export default {
data() {
return {
show: false,
message: '',
type: 'info'
}
},
methods: {
display(message, type = 'info', duration = 3000) {
this.message = message
this.type = type
this.show = true
setTimeout(() => {
this.show = false
}, duration)
}
}
}
</script>
<style scoped>
.toast {
position: fixed;
top: 20px;
right: 20px;
padding: 12px 24px;
border-radius: 4px;
color: white;
z-index: 9999;
}
.info { background-color: #2196F3; }
.success { background-color: #4CAF50; }
.error { background-color: #F44336; }
.warning { background-color: #FF9800; }
</style>
注册为全局组件:
// main.js
import Toast from '@/components/Toast'
const toast = {
install(Vue) {
const ToastConstructor = Vue.extend(Toast)
const instance = new ToastConstructor()
instance.$mount(document.createElement('div'))
document.body.appendChild(instance.$el)
Vue.prototype.$toast = {
show(msg, type, duration) {
instance.display(msg, type, duration)
}
}
}
}
Vue.use(toast)
使用方式:
this.$toast.show('这是一个提示', 'success')
添加动画效果
在 Toast 组件中添加过渡效果:
<template>
<transition name="fade">
<div v-if="show" class="toast" :class="type">
{{ message }}
</div>
</transition>
</template>
<style scoped>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
支持队列显示
修改 Toast 组件的 methods:
methods: {
display(message, type = 'info', duration = 3000) {
this.queue.push({ message, type, duration })
if (!this.isShowing) {
this.showNext()
}
},
showNext() {
if (this.queue.length === 0) {
this.isShowing = false
return
}
this.isShowing = true
const { message, type, duration } = this.queue.shift()
this.message = message
this.type = type
this.show = true
setTimeout(() => {
this.show = false
setTimeout(() => this.showNext(), 300)
}, duration)
}
}
可配置选项扩展
允许通过配置对象自定义 Toast:
this.$toast.show({
message: '自定义内容',
type: 'warning',
duration: 5000,
position: 'bottom-left'
})
在组件中处理位置样式:
<template>
<div v-if="show" class="toast" :class="[type, position]">
{{ message }}
</div>
</template>
<style scoped>
.toast {
/* 原有样式 */
}
.top-right { top: 20px; right: 20px }
.bottom-left { bottom: 20px; left: 20px }
/* 其他位置样式 */
</style>






