vue实现 toast
Vue 实现 Toast 的方法
使用第三方库(推荐)
安装 vue-toastification 库,这是一个功能丰富且易于使用的 Vue Toast 插件。
npm install vue-toastification
在 Vue 项目中全局注册插件:
import Toast from 'vue-toastification'
import 'vue-toastification/dist/index.css'
const app = createApp(App)
app.use(Toast)
在组件中使用 Toast:
this.$toast.success('操作成功')
this.$toast.error('操作失败')
this.$toast.info('提示信息')
this.$toast.warning('警告信息')
自定义 Toast 组件
创建一个可复用的 Toast 组件,适合简单需求。
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>
在组件中使用
import Toast from '@/components/Toast.vue'
export default {
components: { Toast },
methods: {
showToast() {
this.$refs.toast.showToast('自定义Toast消息')
}
}
}
使用 Vue 的 provide/inject
通过 provide/inject 实现全局 Toast 功能。
main.js
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
app.provide('toast', {
show(message, duration = 2000) {
const toast = document.createElement('div')
toast.className = 'toast'
toast.textContent = message
document.body.appendChild(toast)
setTimeout(() => {
document.body.removeChild(toast)
}, duration)
}
})
app.mount('#app')
在组件中使用
export default {
inject: ['toast'],
methods: {
showToast() {
this.toast.show('通过provide/inject实现的Toast')
}
}
}
使用 Vue 3 Composition API
在 Vue 3 中可以使用 Composition API 创建更灵活的 Toast。
useToast.js
import { ref } from 'vue'
export default function useToast() {
const toast = ref({
show: false,
message: ''
})
const showToast = (message, duration = 2000) => {
toast.value.show = true
toast.value.message = message
setTimeout(() => {
toast.value.show = false
}, duration)
}
return { toast, showToast }
}
在组件中使用
<template>
<div v-if="toast.show" class="toast">
{{ toast.message }}
</div>
</template>
<script>
import useToast from '@/composables/useToast'
export default {
setup() {
const { toast, showToast } = useToast()
return { toast, showToast }
}
}
</script>
以上方法提供了不同复杂度的 Toast 实现方案,可以根据项目需求选择合适的方案。第三方库方案功能最完善,自定义组件方案灵活性最高。







