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

InertiaJS对接Laravel控制器后Vue日历切换月份自动回弹到当月问题

问题根因

你的问题本质是Inertia 访问默认会重置组件本地状态:

  • selectedDate 存储在 Vue 组件的data中,初始值为当前日期dayjs()
  • 调用$inertia.visit时如果没有显式配置保留状态,组件会被重新实例化,data会重置为初始值,哪怕已经拿到了对应月份的shifts数据,日历也会因为selectedDate回到当前月而回弹。
  • 没用inertia-link不是问题原因,手动调用visit是官方支持的用法。

解决方案

方案1:显式开启preserveState配置

调用visit时添加preserveState: true,通知 Inertia 保留当前组件的本地状态,不要重置实例:

this.$inertia.visit('calendar', {
    data: {
        newMonth: newMonth,
        newYear: newYear
    },
    preserveState: true
});

如果开启后仍然复位,检查组件的mounted/watch钩子,有没有额外的逻辑在页面更新时强制把selectedDate设为当前日期。

方案2:将选中日期下沉为 Inertia Props(更推荐)

把日期状态交给后端/Inertia props 管理,避免本地状态和 props 不同步:

  1. 修改 Laravel 控制器,将当前查询的年月一同返回:
return Inertia::render('Shifts/CalendarMonth', [
   'shifts' => $thisMonth,
   'queryYear' => $queryYear,
   'queryMonth' => $queryMonth
]);
  1. 前端组件将selectedDate改为通过 props 初始化,不用本地硬编码初始值:
// 组件定义部分
props: {
  queryYear: Number,
  queryMonth: Number,
  shifts: Array
},
data() {
  return {
    selectedDate: dayjs().year(this.queryYear).month(this.queryMonth - 1)
  };
}

方案3:改用$inertia.get简化请求

仅获取数据的场景可以直接用更轻量的get方法,用法和visit一致:

this.$inertia.get('calendar', {
    newMonth: newMonth,
    newYear: newYear
}, {
    preserveState: true
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 13:09:04