vue toast实现
Vue 中实现 Toast 的方法
使用第三方库(推荐) vue-toastification 是一个流行的 Vue Toast 通知库,安装简单且功能丰富。
安装命令:
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 class="toast" v-if="show">
{{ 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;
top: 20px;
right: 20px;
padding: 10px 20px;
background: #333;
color: white;
border-radius: 4px;
z-index: 9999;
}
</style>
在 main.js 中全局注册:
import Toast from '@/components/Toast'
Vue.prototype.$toast = {
install(Vue) {
const ToastClass = Vue.extend(Toast)
const instance = new ToastClass()
instance.$mount(document.createElement('div'))
document.body.appendChild(instance.$el)
Vue.prototype.$toast = (msg, duration) => {
instance.display(msg, duration)
}
}
}
使用 Vuex 管理 Toast 状态 在 store 中创建 toast 模块:
const state = {
show: false,
message: ''
}
const mutations = {
SHOW_TOAST(state, payload) {
state.show = true
state.message = payload.message
},
HIDE_TOAST(state) {
state.show = false
}
}
const actions = {
showToast({ commit }, message) {
commit('SHOW_TOAST', { message })
setTimeout(() => {
commit('HIDE_TOAST')
}, 3000)
}
}
在组件中使用:
this.$store.dispatch('showToast', '操作成功')
注意事项
- 对于简单项目,推荐使用第三方库
- 自定义组件需要考虑动画效果和多种样式
- Vuex 方式适合中大型项目需要全局状态管理的情况
- 移动端项目需要考虑响应式布局和触摸交互







