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)
}
效果如下
相关推荐
满栀58518 小时前
vue动态路由效果
前端·javascript·vue.js·前端框架·vue
碧水澜庭1 天前
头条【vue+fastapi 】全栈教学项目系列之《02_双系统零基础环境搭建手册》
vue·fastapi
DsirNg3 天前
从 `@wheel.prevent.stop` 到事件捕获:一次讲清浏览器事件流与 Vue 事件修饰符
javascript·vue·事件修饰符·事件冒泡·dom 事件·事件捕获·wheel
其美杰布-富贵-李3 天前
Vue 3 模板语法速通:彻底理解 `:`、`@`、`#`、`v-if`、`v-for` 与 `v-model`
vue
DsirNg4 天前
基于拓扑排序的画布自动布局:用最长上游路径决定节点列级
vue·流程图·拓扑排序·状态管理·有向图·自动布局·最长路径
way_hj5 天前
Flask笔记(2)快速web项目
笔记·flask·vue·web
Sterting5 天前
初识Vue3与开发环境搭建
前端·vue
sugar__salt6 天前
跟着 Demo 学 Pinia:两种仓库写法 + 完整 TodoList 复现
前端·javascript·vue.js·前端框架·vue
弹简特6 天前
【Vue3速成】09-Element Plus 核心组件实战与原理解析
vue·element-plus
钛态6 天前
AI 辅助:前端框架反模式:过度封装、状态滥用与副作用失控
前端·vue·react·web