vue 实现toast
vue 实现 toast 的方法
在 Vue 中实现 Toast 提示功能可以通过多种方式完成,以下是几种常见的实现方法:
使用第三方库
Vue 生态中有许多成熟的 Toast 库,如 vue-toastification、vant 等,安装后即可快速使用。
安装 vue-toastification:
npm install vue-toastification@next
在 main.js 中引入并配置:
import Toast from 'vue-toastification'
import 'vue-toastification/dist/index.css'
const app = createApp(App)
app.use(Toast)
在组件中使用:
this.$toast.success('操作成功')
this.$toast.error('操作失败')
自定义全局组件
创建一个全局 Toast 组件,通过 Vue 的插件机制注册为全局方法。
创建 Toast.vue 组件:

<template>
<div v-if="show" class="toast">
{{ message }}
</div>
</template>
<script>
export default {
data() {
return {
show: false,
message: ''
}
},
methods: {
showToast(message, duration = 2000) {
this.message = message
this.show = true
setTimeout(() => {
this.show = false
}, duration)
}
}
}
</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>
注册为全局方法:
// main.js
import Toast from './components/Toast.vue'
const app = createApp(App)
const toast = createApp(Toast).mount(document.createElement('div'))
document.body.appendChild(toast.$el)
app.config.globalProperties.$toast = {
show: (msg, duration) => toast.showToast(msg, duration)
}
在组件中使用:
this.$toast.show('这是一个提示')
使用 Vue 3 的 Composition API
在 Vue 3 中可以利用 provide/inject 或组合式函数实现更灵活的 Toast。
创建 useToast.js:

import { ref } from 'vue'
export function useToast() {
const toast = ref({
show: false,
message: ''
})
const showToast = (message, duration = 2000) => {
toast.value.message = message
toast.value.show = true
setTimeout(() => {
toast.value.show = false
}, duration)
}
return { toast, showToast }
}
在组件中使用:
<template>
<div v-if="toast.show" class="toast">
{{ toast.message }}
</div>
<button @click="showToast('Hello')">显示 Toast</button>
</template>
<script>
import { useToast } from './useToast'
export default {
setup() {
const { toast, showToast } = useToast()
return { toast, showToast }
}
}
</script>
使用 Teleport 实现
Vue 3 的 Teleport 可以方便地将 Toast 渲染到 body 或其他指定位置。
创建 Toast.vue:
<template>
<teleport to="body">
<div v-if="show" class="toast">
{{ message }}
</div>
</teleport>
</template>
<script>
export default {
data() {
return {
show: false,
message: ''
}
},
methods: {
showToast(message, duration = 2000) {
this.message = message
this.show = true
setTimeout(() => {
this.show = false
}, duration)
}
}
}
</script>
注册为全局组件后即可在任何地方使用。
注意事项
- 样式需要根据项目需求自定义,包括位置、动画效果等
- 考虑添加多种类型(success、error、warning 等)和图标支持
- 对于频繁触发的 Toast,需要处理队列或防抖
- 移动端需要考虑适配合适的显示位置和样式






