使用 laravel + Inertia.js + vue 可快速构建 SPA。1. 创建 Laravel 项目并安装 inertiajs/inertia-laravel;2. 安装 vue@next 与 @inertiajs/inertia-vue3,配置 resources/js/app.js 初始化 Inertia 与 Vue;3. 创建 Vue 页面组件于 resources/js/Pages/;4. 在 web.php 中使用 Inertia::render() 返回页面;5. 配置 vite.config.js 并通过 @vite 引入资源;6. 运行 php artisan serve 启动服务,实现无刷新路由跳转。

使用 Laravel 结合 Inertia.js 和 Vue 构建单页应用(SPA),可以让你在不编写 API 路由的情况下,享受前后端无缝衔接的开发体验。Inertia.js 的核心作用是桥接后端框架(如 Laravel)与前端 javaScript 框架(如 Vue),无需传统 REST API 即可渲染 Vue 页面。以下是具体实现方法。
1. 环境准备与项目初始化
确保已安装 Laravel 并创建好项目:
composer create-project laravel/laravel inertia-app
cd inertia-app
接着安装 Inertia 服务端支持包:
composer require inertiajs/inertia-laravel
2. 安装并配置前端依赖(Vue + Inertia)
进入项目根目录,使用 npm 安装 Vue 和 Inertia 相关包:
立即学习“前端免费学习笔记(深入)”;
npm install vue@next @inertiajs/inertia @inertiajs/inertia-vue3
创建前端入口文件。在 resources/js/app.js 中初始化 Inertia 和 Vue:
import { createApp, h } from ‘vue’
import { createInertiaApp } from ‘@inertiajs/inertia-vue3’
import { InertiaProgress } from ‘@inertiajs/progress’
createInertiaApp({
resolve: name => require(`./Pages/${name}.vue`),
setup({ el, App, props }) {
createApp({ render: () => h(App, props) }).mount(el)
}
})
// 显示页面切换进度条
InertiaProgress.init()
然后创建一个根模板文件:resources/views/app.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Inertia App</title>
</head>
<body>
@inertia
</body>
</html>
注意:@inertia 指令会自动注入 Inertia 应用容器和初始页面数据。
3. 创建 Vue 页面组件
在 resources/js/Pages/ 目录下创建 Vue 页面,例如 Home.vue:
<template>
<div>
<h1>欢迎使用 Inertia + Vue 单页应用</h1>
<inertia-link href=”/about”>前往关于页</inertia-link>
</div>
</template>
<script>
export default {
name: ‘Home’
}
</script>
再创建 About.vue:
<template>
<div>
<h1>关于页面</h1>
<inertia-link href=”/”>返回首页</inertia-link>
</div>
</template>
4. 配置 Laravel 路由返回 Inertia 页面
修改 routes/web.php,使用 Inertia::render() 返回 Vue 页面:
use InertiaInertia;
Route::get(‘/’, function () {
return Inertia::render(‘Home’);
});
Route::get(‘/about’, function () {
return Inertia::render(‘About’);
});
Inertia::render(‘Home’) 会自动加载 resources/js/Pages/Home.vue 组件。
5. 编译前端资源
配置 Vite 或 Laravel Mix 来编译 JS/css。以 Vite 为例(Laravel 9+ 默认使用 Vite):
编辑 vite.config.js:
import { defineConfig } from ‘vite’;
import laravel from ‘laravel-vite-plugin’;
import vue from ‘@vitejs/plugin-vue’;
export default defineConfig({
plugins: [
laravel({
input: [‘resources/css/app.css’, ‘resources/js/app.js’],
refresh: true,
}),
vue({
reactivityTransform: true
}),
],
});
运行编译命令:
npm run dev
确保在 resources/views/app.blade.php 中引入编译后的资源:
<head>
@vite([‘resources/js/app.js’])
</head>
6. 启动应用并测试 SPA 效果
启动 Laravel 开发服务器:
php artisan serve
访问 http://localhost:8000,点击链接跳转到 /about,你会发现页面无刷新切换 —— 这就是 Inertia 实现的单页应用效果。
Inertia 会通过 XHR 请求获取新页面的 json 数据,并交由 Vue 渲染,整个过程无需全量刷新。
基本上就这些。你已经成功构建了一个基于 Laravel + Inertia.js + Vue 的单页应用。后续可以添加布局、中间件、表单提交、共享数据等高级功能。关键是理解 Inertia 扮演的“中间人”角色:它让 Laravel 控制器决定渲染哪个 Vue 页面,同时保持 SPA 体验。不复杂但容易忽略细节。


