vue 实现toast组件
实现 Vue Toast 组件的方法
创建基础 Toast 组件
在 Vue 项目中创建一个基础 Toast 组件,通常包含消息内容和显示控制逻辑。
<template>
<div v-if="visible" class="toast">
{{ message }}
</div>
</template>
<script>
export default {
name: 'Toast',
data() {
return {
visible: false,
message: ''
}
},
methods: {
show(message, duration = 2000) {
this.message = message
this.visible = true
setTimeout(() => {
this.visible = false
}, duration)
}
}
}
</script>
<style>
.toast {
position: fixed;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
padding: 10px 20px;
background-color: rgba(0, 0, 0, 0.7);
color: white;
border-radius: 4px;
z-index: 9999;
}
</style>
全局注册 Toast 服务
将 Toast 组件注册为全局服务,方便在任何组件中调用。
// src/plugins/toast.js
import Vue from 'vue'
import Toast from '@/components/Toast.vue'
const ToastConstructor = Vue.extend(Toast)
let toastInstance = null
function showToast(message, duration) {
if (!toastInstance) {
toastInstance = new ToastConstructor({
el: document.createElement('div')
})
document.body.appendChild(toastInstance.$el)
}
toastInstance.show(message, duration)
}
export default {
install(Vue) {
Vue.prototype.$toast = showToast
}
}
在 main.js 中安装插件
// src/main.js
import Vue from 'vue'
import Toast from '@/plugins/toast'
Vue.use(Toast)
在组件中使用 Toast
// 在任何组件中调用
this.$toast('这是一条提示消息', 3000)
添加动画效果
为 Toast 添加淡入淡出动画效果。
.toast {
/* 其他样式 */
opacity: 0;
transition: opacity 0.3s ease;
}
.toast.show {
opacity: 1;
}
修改组件逻辑支持动画
methods: {
show(message, duration = 2000) {
this.message = message
this.visible = true
this.$nextTick(() => {
this.$el.classList.add('show')
setTimeout(() => {
this.$el.classList.remove('show')
setTimeout(() => {
this.visible = false
}, 300)
}, duration)
})
}
}
支持多种类型
扩展 Toast 支持 success、error、warning 等不同类型。
<template>
<div v-if="visible" :class="['toast', `toast-${type}`]">
<span class="toast-icon">{{ iconMap[type] }}</span>
{{ message }}
</div>
</template>
<script>
export default {
data() {
return {
type: 'info',
iconMap: {
info: 'ℹ️',
success: '✅',
warning: '⚠️',
error: '❌'
}
}
},
methods: {
show(message, type = 'info', duration = 2000) {
this.type = type
this.message = message
this.visible = true
// 其他逻辑
}
}
}
</script>
<style>
.toast-success {
background-color: rgba(76, 175, 80, 0.9);
}
.toast-error {
background-color: rgba(244, 67, 54, 0.9);
}
.toast-warning {
background-color: rgba(255, 193, 7, 0.9);
}
.toast-icon {
margin-right: 8px;
}
</style>
更新全局服务
function showToast(message, options = {}) {
const { type = 'info', duration = 2000 } = options
if (!toastInstance) {
toastInstance = new ToastConstructor({
el: document.createElement('div')
})
document.body.appendChild(toastInstance.$el)
}
toastInstance.show(message, type, duration)
}
Vue.prototype.$toast = (message, options) => {
if (typeof options === 'number') {
showToast(message, { duration: options })
} else {
showToast(message, options)
}
}
使用示例
this.$toast('操作成功', { type: 'success', duration: 3000 })
this.$toast('发生错误', 'error')
this.$toast('普通提示', 2000)






