当前位置:首页 > VUE

vue toast实现

2026-01-13 04:03:05VUE

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)

在组件中使用:

vue toast实现

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 中全局注册:

vue toast实现

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 方式适合中大型项目需要全局状态管理的情况
  • 移动端项目需要考虑响应式布局和触摸交互

标签: vuetoast
分享给朋友:

相关文章

vue里实现增删改查

vue里实现增删改查

在Vue中实现增删改查 数据初始化 在Vue组件的data中定义初始数据和表单绑定的变量: data() { return { items: [ { id: 1, name:…

vue实现iframe

vue实现iframe

Vue 中实现 iframe 的方法 在 Vue 项目中,可以通过多种方式实现 iframe 的嵌入。以下是几种常见的方法: 使用原生 HTML iframe 标签 直接在 Vue 组件的模板中使用…

vue实现管道

vue实现管道

Vue 中实现管道(Pipe)功能 在 Vue 中可以通过过滤器(Filters)或计算属性(Computed Properties)实现类似管道的功能,将数据经过多个处理步骤后输出。 使用过滤器(…

vue实现水印

vue实现水印

Vue 实现水印的方法 使用 CSS 背景图 通过 CSS 的 background-image 和 background-repeat 属性实现水印效果。创建一个包含水印文本的 Canvas,将其转…

vue滚动实现

vue滚动实现

Vue 滚动实现方法 使用原生滚动 在 Vue 中可以通过 ref 获取 DOM 元素,调用原生滚动方法实现滚动效果。适用于简单场景。 <template> <div ref=…

vue实现menu

vue实现menu

Vue 实现 Menu 的方法 使用 Element UI 的 Menu 组件 Element UI 提供了现成的 Menu 组件,适合快速实现导航菜单。安装 Element UI 后,可以直接使用…