Vue3 vant4 解决引入的Toast和dialog样式丢失的bug

情景再现:
正确做法:

import 'vant/es/toast/style'

import 'vant/es/dialog/style'

TypeScript 复制代码
import type { App } from 'vue'
import { showToast, type ToastOptions, closeToast, showDialog, type DialogOptions } from 'vant'
import 'vant/es/toast/style'
import 'vant/es/dialog/style'

// 全局消息提示
export const $toast = {
  text: (
    content: string,
    options: ToastOptions = {
      duration: 2000
    }
  ) =>
    showToast({
      message: content,
      ...options
    }),
  loading: (
    content: string,
    options: ToastOptions = {
      duration: 2000
    }
  ) =>
    showToast({
      message: content,
      type: 'loading',
      ...options
    }),
  success: (
    content: string,
    options: ToastOptions = {
      duration: 2000
    }
  ) =>
    showToast({
      message: content,
      type: 'success',
      ...options
    }),
  error: (
    content: string,
    options: ToastOptions = {
      duration: 2000
    }
  ) =>
    showToast({
      message: content,
      type: 'fail',
      ...options
    }),
  closeAll: () => {
    closeToast()
  }
}

// 全局确认框
export const $confirm = (content: string, options?: DialogOptions) => {
  return showDialog({
    title: options?.title || '提示',
    message: content,
    confirmButtonText: options?.confirmButtonText || '确定',
    cancelButtonText: options?.cancelButtonText || '取消',
    ...options
  })
}

// Vant 安装函数
export default function setupVant(app: App<Element>) {
  // 挂载到全局属性
  app.config.globalProperties.$toast = $toast
  app.config.globalProperties.$confirm = $confirm

  // 挂载到 window 对象,供其他模块使用
  if (typeof window !== 'undefined') {
    ;(window as any).$toast = $toast
    ;(window as any).$confirm = $confirm
  }

  // 提供给组合式 API 使用
  app.provide('$toast', $toast)
  app.provide('$confirm', $confirm)
}
效果如下
相关推荐
汤米粥4 天前
2026年主流前端技术框架
vue·react·elementplus·tailwind css·angular‌·svelte‌·bootstrap‌
codigger4 天前
Vue nextTick 到底在等什么?一篇讲透原理与那些年踩过的坑
程序员·vue·编程·异步更新·#人工智能
咚咚咚小柒5 天前
【前端】LangChain.js学习
前端·javascript·人工智能·typescript·langchain·vue·ai编程
悟道书生7 天前
若依 RBAC 权限控制学习笔记
java·网络·笔记·sql·学习·vue
mewowaBc7 天前
使用Pinia持久化存储实现用户认证系统
vue·pinia·用户认证系统
gc_22997 天前
使用VS Code终端创建Vue项目报错:“npm : 无法加载文件 ...\npm.ps1,因为在此系统上禁止运行脚本”
vue·vs code
小阿鑫8 天前
尤雨溪 : Vue 4 已经在规划中了!
vue·vite·vite+·程序员海军·vue4
离歌漠8 天前
《我用 Tauri 做了一个本地开发工具箱》
rust·typescript·vue
enjoy编程9 天前
playwright学习-I
typescript·vue·nodejs·1024程序员节·playwright
落花看风雪11 天前
从零开始搭建后台系统(vue3+TypeScript+Vite)01
typescript·vue·js