迁移至Nuxt3后使用Vue Toastification遇依赖过时错误求助
Nuxt3 替换 @nuxtjs/toast 解决Vue Toastification依赖兼容问题
问题根源
Vue Toastification旧版本适配Vue2,直接在Nuxt3(Vue3环境)中使用会触发依赖过时报错,必须安装Vue3兼容版本。
解决步骤
- 卸载已安装的旧版Vue Toastification(若之前安装过)
npm uninstall vue-toastification # 使用yarn的话执行 yarn remove vue-toastification
- 安装Vue3兼容版
npm install vue-toastification@next # 使用yarn的话执行 yarn add vue-toastification@next
- 配置Nuxt3客户端插件
在项目plugins目录下新建toast.client.ts文件(.client后缀确保仅在客户端加载):
import Toast from 'vue-toastification' import 'vue-toastification/dist/index.css' export default defineNuxtPlugin((nuxtApp) => { nuxtApp.vueApp.use(Toast, { // 可自定义配置项,示例如下 position: 'top-right', timeout: 3000, closeOnClick: true, pauseOnHover: true }) })
- 在组件中调用使用
<script setup> const { $toast } = useNuxtApp() const showSuccess = () => { $toast.success('操作完成!') } const showError = () => { $toast.error('出错了,请检查后重试') } </script> <template> <button @click="showSuccess">成功提示</button> <button @click="showError">错误提示</button> </template>
- TypeScript类型补充(可选)
若项目使用TS,在types目录新建toast.d.ts完善类型提示:
import type { ToastInterface } from 'vue-toastification' declare module '#app' { interface NuxtApp { $toast: ToastInterface } } export {}
内容的提问来源于stack exchange,提问作者Ali Nawaz
相关产品推荐
相关产品推荐

