You need to enable JavaScript to run this app. Laravel使用vue.js提交表单后重定向并传递flash消息的实现问题
优惠活动
大模型
产品
解决方案
定价
更多

Laravel使用vue.js提交表单后重定向并传递flash消息的实现问题

解决方案

你的场景属于页面全量跳转后的消息传递,两种方案都可以快速实现需求:

方案1:使用localStorage临时存储消息(推荐,改造成本最低)

利用前端本地存储在页面跳转后不会丢失的特性传递临时提示消息:

  1. 修改Create.vue的提交成功逻辑:
.then(response => {
    // 把提示消息存入本地存储
    localStorage.setItem('service_alert', response.data.alert_store)
    window.location.href = '/admin/services';
})
  1. 修改Index.vue的mounted钩子,读取并消费消息:
mounted() {
    this.loadServices()
    // 读取本地存储的提示消息
    const alertMsg = localStorage.getItem('service_alert')
    if(alertMsg){
        this.alert_success = alertMsg
        this.success.push(Alert)
        // 消费完成后立即删除,避免下次刷新重复提示
        localStorage.removeItem('service_alert')
    }
},

方案2:使用Laravel原生Session闪存

借助服务端session闪存特性传递消息,适合对安全性要求更高的场景:

  1. 修改后端store方法,新增session闪存逻辑:
public function store(Request $request)
{
    Service::create([
         'name' => $request->get('name'),
         'vendor_id' => $request->get('vendor'),
         'desc' => $request->get('desc'),
         'hours' => $request->get('hours'),
         'price_per_hour' => $request->get('price'),
         'fixed_price' => $request->get('fixed_price'),
         'user_id' => $request->user()->id
     ]);
    // 闪存消息到session
    session()->flash('alert_store', 'New service added successfully.');

     if (\request()->wantsJson()) {
        return response()->json([
             'status' => 'success'
        ]);
    }
}
  1. 在渲染Index组件的blade文件中,把session值传给组件prop:
<index :alert-store="{{ json_encode(session('alert_store', '')) }}"></index>
  1. 修改Index.vue的mounted钩子,直接使用prop传入的消息:
mounted() {
    this.loadServices()
    if(this.alert_store){
        this.alert_success = this.alert_store
        this.success.push(Alert)
    }
},

注意事项

  • localStorage属于客户端存储,不要用它传递敏感信息,仅用于存储普通提示消息无安全问题
  • 用session方案需要确保你的路由在web中间件组下,否则session不会生效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 07:24:02