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

在Laravel+Vue项目中无刷新更新Inertia全局变量

在Inertia + Vue中无需刷新页面更新共享的全局变量'foo'

当然可以实现,以下是两种常用方案:

方案一:利用Inertia的reload方法局部更新Props

Inertia提供了reload方法,能在不刷新浏览器的情况下重新请求当前页面,并指定只更新特定的props。这样后端HandleInertiaRequests的share方法会重新执行生成新的foo值,Inertia会自动更新前端的$page.props。

修改你的Vue组件代码:

<script setup>
import { usePage } from '@inertiajs/vue3'

const page = usePage()

const updateFoo = () => {
  // 仅更新'foo'这个prop,避免不必要的资源加载
  page.reload({ only: ['foo'] })
}
</script>

<template>
  {{ $page.props.foo }}
  <button @click="updateFoo" type="button">update</button>
</template>

方案二:通过API接口单独获取新值并手动更新

如果不想重新触发整个页面的props加载,可以单独写一个后端接口返回新的foo值,前端调用接口后直接更新$page.props。

第一步:添加后端API路由

在你的Laravel路由文件(如routes/web.php)中新增接口:

Route::get('/refresh-foo', function () {
    return response()->json([
        'foo' => str()->random(1000)
    ]);
});

第二步:修改Vue组件调用接口

<script setup>
import { usePage } from '@inertiajs/vue3'
import axios from 'axios'

const page = usePage()

const updateFoo = async () => {
  try {
    const res = await axios.get('/refresh-foo')
    // 直接更新page.props中的foo,Vue会自动响应式渲染新值
    page.props.foo = res.data.foo
  } catch (err) {
    console.error('更新失败:', err)
  }
}
</script>

<template>
  {{ $page.props.foo }}
  <button @click="updateFoo" type="button">update</button>
</template>

两种方案对比:

  • 方案一更简洁,依赖Inertia的内置能力,适合需要同步多个props的场景;
  • 方案二更灵活,仅更新单个变量,性能更优,适合只需要更新特定值的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 19:04:59