You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue-Toastification嵌入Vuetify组件时默认实例加载失败问题

在Vue Toastification中使用Vuetify组件的问题解决

问题描述

我尝试在vue-toastification的弹窗中使用包含Vuetify组件的自定义组件,操作流程如下:

  • 通过npm create vuetify@latest创建项目
  • 安装vue-toastification@latest后,在main.ts中配置插件并设置shareAppContext: true
  • 在Pinia的error store中调用toast展示自定义组件MyComponent(该组件内使用v-container、v-row等Vuetify组件)
  • 点击App.vue中的按钮触发弹窗时,出现[Vuetify] Could not find defaults instance等报错

疑问:遗漏了什么配置?运行时动态加载的组件中无法使用Vuetify吗?

问题原因

尽管设置了shareAppContext: true让Toast共享应用上下文,但Vuetify的默认配置实例并未被正确注入到动态渲染的Toast组件中。Vue Toastification的动态组件渲染流程里,Vuetify的全局配置没有完全传递到目标组件。

解决步骤

1. 手动在自定义组件中注入Vuetify实例

在自定义组件MyComponent.vue中,手动引入并获取Vuetify实例,确保组件能访问到Vuetify配置:

<script setup>
import { useVuetify } from 'vuetify'

// 手动获取Vuetify实例
const vuetify = useVuetify()
</script>

2. 调整插件注册顺序与配置

确保在main.ts中先注册Vuetify插件,再注册Vue Toastification,同时确认shareAppContext已正确开启:

// main.ts
import { createApp } from 'vue'
import App from './App.vue'
import { createVuetify } from 'vuetify'
import * as components from 'vuetify/components'
import * as directives from 'vuetify/directives'
import Toast, { POSITION } from "vue-toastification";
import "vue-toastification/dist/index.css";

const vuetify = createVuetify({
  components,
  directives,
})

const app = createApp(App)
app.use(vuetify) // 优先注册Vuetify
app.use(Toast, {
  position: POSITION.BOTTOM_RIGHT,
  shareAppContext: true // 确保开启上下文共享
})
app.mount('#app')

3. 优化Toast调用方式(可选)

建议在组件中直接调用Toast,若需要在Pinia store中调用,确保使用正确的Toast实例:

// error store
import { defineStore } from 'pinia'
import { useToast } from 'vue-toastification'

export const useErrorStore = defineStore('error', {
  actions: {
    showErrorToast() {
      const toast = useToast()
      toast.info(import('./MyComponent.vue'))
    }
  }
})

补充说明

运行时动态加载的组件完全可以使用Vuetify,核心问题是动态渲染的Toast组件没有正确获取到Vuetify的全局配置实例。通过手动注入Vuetify实例,即可解决Could not find defaults instance的报错。

内容的提问来源于stack exchange,提问作者Daniele Tentoni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 20:05:24