vue实现 toast
Vue 实现 Toast 组件
在 Vue 中实现 Toast 组件可以通过多种方式完成,以下是几种常见的方法:
使用全局组件和事件总线
创建一个全局的 Toast 组件,并通过事件总线或 Vue 实例方法来触发显示。
- 创建 Toast 组件
<template> <div v-if="visible" class="toast"> {{ message }} </div> </template>
- 注册为全局组件并添加实例方法
// main.js import Vue from 'vue' import Toast from './components/Toast.vue'
const ToastConstructor = Vue.extend(Toast) const toastInstance = new ToastConstructor({ el: document.createElement('div') }) document.body.appendChild(toastInstance.$el)
Vue.prototype.$toast = (message, duration) => { toastInstance.show(message, duration) }
3. 在组件中使用
```js
this.$toast('操作成功', 2000)
使用插件方式封装
将 Toast 封装为 Vue 插件,提供更灵活的调用方式。
-
创建 toast.js 插件
const Toast = { install(Vue) { const ToastConstructor = Vue.extend(require('./Toast.vue').default) const toastInstance = new ToastConstructor() toastInstance.$mount(document.createElement('div')) document.body.appendChild(toastInstance.$el) Vue.prototype.$toast = (message, duration = 3000) => { toastInstance.show(message, duration) } } }
export default Toast
2. 在 main.js 中使用插件
```js
import Toast from './plugins/toast'
Vue.use(Toast)
- 调用方式与之前相同
this.$toast('消息内容')
使用第三方库
如果不想自己实现,可以使用现有的 Vue Toast 库:
-
vue-toastification
npm install vue-toastification@next -
配置使用
import Toast from 'vue-toastification' import 'vue-toastification/dist/index.css'
Vue.use(Toast, { transition: 'Vue-Toastification__bounce', maxToasts: 5, newestOnTop: true })
3. 调用方式
```js
this.$toast.success('操作成功')
this.$toast.error('发生错误')
this.$toast.info('提示信息')
使用 Composition API 实现
在 Vue 3 中可以使用 Composition API 实现更灵活的 Toast。
- 创建 useToast.js
import { ref } from 'vue'
export function useToast() { const toasts = ref([])
const showToast = (message, duration = 3000) => { const toast = { id: Date.now(), message } toasts.value.push(toast) setTimeout(() => { toasts.value = toasts.value.filter(t => t.id !== toast.id) }, duration) }
return { toasts, showToast } }
2. 在组件中使用
```vue
<template>
<div class="toast-container">
<div v-for="toast in toasts" :key="toast.id" class="toast">
{{ toast.message }}
</div>
</div>
</template>
<script>
import { useToast } from './useToast'
export default {
setup() {
const { toasts, showToast } = useToast()
return {
toasts,
showToast
}
}
}
</script>
以上方法可以根据项目需求选择适合的实现方式。全局组件方式适合简单需求,插件方式更规范,第三方库功能最全面,Composition API 方式最适合 Vue 3 项目。







