vue实现toast
实现 Vue Toast 的方法
在 Vue 中实现 Toast 提示功能可以通过多种方式完成,以下是几种常见的实现方法:
使用第三方库
Vue 生态中有许多成熟的 Toast 组件库,例如 vue-toastification 或 vant 提供的 Toast 组件,安装后直接使用:

npm install vue-toastification
// main.js
import Toast from 'vue-toastification'
import 'vue-toastification/dist/index.css'
Vue.use(Toast)
// 组件中使用
this.$toast.success("操作成功")
this.$toast.error("操作失败")
自定义全局组件
通过 Vue 的插件机制自定义一个全局 Toast 组件:

// Toast.vue
<template>
<div v-if="show" class="toast">
{{ message }}
</div>
</template>
<script>
export default {
data() {
return {
show: false,
message: ''
}
}
}
</script>
<style>
.toast {
position: fixed;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
background: rgba(0,0,0,0.7);
color: white;
padding: 10px 20px;
border-radius: 4px;
z-index: 9999;
}
</style>
// toast.js
import Vue from 'vue'
import ToastComponent from './Toast.vue'
const ToastConstructor = Vue.extend(ToastComponent)
function showToast(text, duration = 2000) {
const toastDom = new ToastConstructor({
el: document.createElement('div'),
data() {
return {
show: true,
message: text
}
}
})
document.body.appendChild(toastDom.$el)
setTimeout(() => {
toastDom.show = false
setTimeout(() => {
document.body.removeChild(toastDom.$el)
}, 300)
}, duration)
}
export default showToast
// main.js
import toast from './toast'
Vue.prototype.$toast = toast
使用 Vuex 管理状态
对于需要复杂状态管理的应用,可以使用 Vuex 来统一管理 Toast 的显示状态:
// store.js
const store = new Vuex.Store({
state: {
toast: {
show: false,
message: ''
}
},
mutations: {
showToast(state, payload) {
state.toast.show = true
state.toast.message = payload.message
setTimeout(() => {
state.toast.show = false
}, payload.duration || 2000)
}
}
})
// 组件中使用
this.$store.commit('showToast', {
message: '操作成功',
duration: 1500
})
使用 Composition API
在 Vue 3 中可以使用 Composition API 创建响应式的 Toast 功能:
// useToast.js
import { ref } from 'vue'
export function useToast() {
const show = ref(false)
const message = ref('')
function toast(msg, duration = 2000) {
message.value = msg
show.value = true
setTimeout(() => {
show.value = false
}, duration)
}
return { show, message, toast }
}
// 组件中使用
const { show, message, toast } = useToast()
toast('这是一个提示')
每种方法都有其适用场景,第三方库适合快速集成,自定义组件灵活性更高,Vuex 适合大型应用状态管理,Composition API 则更适合 Vue 3 项目。






