在Inertia.js项目中使用vue-toastr无法生效该如何解决?
问题排查与解决方案
- 确认版本适配
你当前使用的是适配Vue2的Inertia适配器,必须安装对应Vue2的vue-toastr版本,运行命令:npm install vue-toastr@2 --save
如果之前安装了3.x版本的vue-toastr,该版本仅适配Vue3,和Vue2环境不兼容,会直接导致调用失败。 - 引入配套样式
vue-toastr需要引入单独的样式文件才能正常显示弹窗,在app.js中添加引入代码:
import 'vue-toastr/dist/vue-toastr.css'
修改后的完整app.js代码如下:
import Vue from 'vue' import { createInertiaApp } from '@inertiajs/inertia-vue' import Toastr from 'vue-toastr' // 引入toastr样式 import 'vue-toastr/dist/vue-toastr.css' Vue.use(Toastr); createInertiaApp({ resolve: name => require(`./Pages/${name}`), setup({ el, App, props }) { new Vue({ render: h => h(App, props), }).$mount(el) }, })
- 添加渲染容器
vue-toastr需要在页面中渲染对应的组件标签才能绑定全局实例,你可以直接在全局Master布局组件的模板最外层添加标签:
<template> <div class="master-layout"> <!-- toastr渲染容器 --> <vue-toastr /> <!-- 原有布局逻辑 --> <slot /> </div> </template>
- 调整调用时机(可选)
如果执行上述步骤后仍不生效,可以将toastr的调用逻辑从created钩子转移到mounted钩子,避免组件未完成挂载就调用方法:
<script> import Master from './Layout/Master'; export default{ name:"Home", mounted(){ this.$toastr.s("success","it is working"); }, components:{Master} }; </script>
内容的提问来源于stack exchange,提问作者Nay Lin Htet
相关产品推荐
相关产品推荐

