Laravel中使用Redirect::route跳转后Inertia无法显示Flash消息
解决Inertia跨路由跳转时SweetAlert2不触发Flash提示的问题
问题原因
你用watch监听swalFlash和swalErrors,但watch仅在数据发生变更时执行回调。通过Redirect::route()跳转到新路由时,Swal组件是全新挂载的,此时传入的swalFlash/swalErrors是初始值,没有发生"变化",所以watch的handler不会触发;而Redirect::back()时组件是复用的,数据更新会触发watch,因此提示正常。
解决方案
修改Swal.vue,在组件挂载时手动检查一次数据,同时优化watch的深度监听:
<template> </template> <script> export default { props: { swalErrors: Object, swalFlash: Object }, mounted() { // 组件挂载时手动初始化检查 this.checkAndShowAlerts() }, watch: { swalErrors: { handler: function () { this.checkAndShowAlerts() }, deep: true // 监听对象内部属性变化 }, swalFlash: { handler: function () { this.checkAndShowAlerts() }, deep: true // 监听对象内部属性变化 } }, methods: { checkAndShowAlerts() { // 处理错误提示 if (this.swalErrors && Object.keys(this.swalErrors).length > 0) { this.toast(Object.values(this.swalErrors).join(' ')) } // 处理Flash提示 if (this.swalFlash && this.swalFlash.message) { this.toast(this.swalFlash.message, this.swalFlash.title, this.swalFlash.type) } }, toast: function (html, title, icon, timer) { title = title || 'Error'; icon = icon || 'error'; timer = timer || 4000; this.$swal.fire({ position: 'top-end', toast: true, icon: icon, title: title, html: html, showClass: { popup: 'animate__animated animate__fadeInDown' }, hideClass: { popup: 'animate__animated animate__fadeOutUp' }, timer: timer, timerProgressBar: true, showConfirmButton: false, }); } } } </script>
修改说明
- mounted钩子初始化检查:组件挂载时立即执行
checkAndShowAlerts,确保跨路由跳转时已存在的flash/errors能触发提示 - 添加deep: true:因为
swalFlash和swalErrors是对象,开启深度监听后,对象内部属性的变化也能触发watch回调 - 统一检查逻辑:把错误和flash的检查逻辑抽离到
checkAndShowAlerts方法,避免代码重复
内容的提问来源于stack exchange,提问作者Kaizokupuffball
相关产品推荐
相关产品推荐

