当前位置:首页 > 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)

在组件中使用:

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

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

vue toast实现

标签: vuetoast
分享给朋友:

相关文章

vue实现autocomplete

vue实现autocomplete

Vue 实现 Autocomplete 功能 Vue 中实现 Autocomplete(自动完成)功能可以通过自定义组件或使用现有库完成。以下是几种常见方法: 方法一:使用 Vue 原生实现 创建…

vue架构实现

vue架构实现

Vue 架构实现核心方案 Vue.js 的架构实现通常围绕模块化、组件化和状态管理展开。以下为常见实现方案: 基于单文件组件(SFC)的模块化 通过 .vue 文件组织模板、脚本和样式: <…

vue实现节流

vue实现节流

vue实现节流的方法 在Vue中实现节流(throttle)功能,通常用于限制高频事件的触发频率,例如滚动、输入或按钮点击。以下是几种常见的实现方式: 使用Lodash的throttle函数 安装…

vue实现签章

vue实现签章

Vue 实现签章功能 签章功能通常包括手写签名、电子印章等。以下是基于 Vue 的实现方法: 使用 canvas 实现手写签名 安装依赖(如需要): npm install signature…

tabbar 实现 vue

tabbar 实现 vue

在 Vue 中实现 TabBar 功能可以通过多种方式完成,以下是几种常见的方法: 使用 Vue Router 结合自定义组件 创建一个自定义的 TabBar 组件,结合 Vue Route…

vue computed实现

vue computed实现

计算属性的基本用法 在Vue中,计算属性通过computed选项定义,用于声明依赖于其他属性的动态值。计算属性基于它们的依赖进行缓存,只有依赖发生变化时才会重新计算。 new Vue({ da…