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

Laravel Inertia JS重复触发Flash消息失效问题求助

解决InertiaJS同路由下Flash消息重复触发问题

问题核心是InertiaJS在同路由导航时不会重新挂载组件,当前组件仅在onMounted阶段触发消息显示,后续后端返回的Flash消息无法触发显示逻辑,导致重复操作时消息不再出现。

修改Flash消息组件

替换原组件的<script setup>部分,通过监听message的变化重新触发消息显示,并清理旧定时器避免冲突:

<script setup>
import { ref, onMounted, watch, onUnmounted } from "vue";
defineProps({
    message: Object,
});

const showNotif = ref(false);
let timer = null;

// 统一处理消息显示逻辑
const triggerNotification = () => {
    // 清理之前的定时器,避免叠加
    if (timer) clearTimeout(timer);
    showNotif.value = true;
    // 6秒后自动隐藏
    timer = setTimeout(() => {
        showNotif.value = false;
    }, 6000);
};

onMounted(() => {
    // 初始挂载时若有消息则显示
    if (message.error || message.success) {
        triggerNotification();
    }
});

// 监听message的深层变化,有新消息就触发显示
watch(message, (newMsg) => {
    if (newMsg.error || newMsg.success) {
        triggerNotification();
    }
}, { deep: true });

// 组件卸载时清理定时器,防止内存泄漏
onUnmounted(() => {
    if (timer) clearTimeout(timer);
});
</script>

关键修改说明

  • 新增watch监听message的深层变化,只要后端返回新的error或success,就重新触发消息显示
  • 封装triggerNotification函数统一处理显示逻辑,每次触发前清理旧定时器,避免多个定时器叠加导致的异常
  • 组件卸载时清理定时器,防止内存泄漏
  • 初始挂载时判断消息存在性,确保首次加载正常显示

修改后,重复执行同一失败操作时,后端返回的Flash消息会触发监听逻辑,重新显示通知。

内容的提问来源于stack exchange,提问作者Mostafa Said

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 12:18:21