手动从零开始构建Laravel8+Inertiajs+Vue3项目

原文发布在我的博客:Laravel 中使用 Inertiajs + Vue3 初始化项目
Inertiajs 中文文档翻译工作已经完成,文档地址:Inertiajs中文文档

官方文档中没有说明如何在 Laravel8 中开始正确使用 Inertiajs 初始化一个项目,我在谷歌也找了很多文章,没有找到说的很清楚的,基本都是把文档中服务器端和客户端的手册复制了一遍。自己摸索了一下,遇到了一些问题都解决了,最终搭建成功,把过程记录一下,以供参考。

服务器端配置

初始化 Laravel 项目
laravel new laravel

cd laravel
安装 inertia-laravel
composer require inertiajs/inertia-laravel
创建根模板

reources/views 下创建 app.blade.php 文件,并添加以下内容。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
    <link href="{{ mix('/css/app.css') }}" rel="stylesheet" />
    <script src="{{ mix('/js/app.js') }}" defer></script>
  </head>
  <body>
    @inertia
  </body>
</html>
设置中间件
php artisan inertia:middleware

生成中间件后,在 App\Http\Kernel 中注册 HandleInertiaRequests 中间件,作为 web 中间件组中的最后一项。

'web' => [
    // ...
    \App\Http\Middleware\HandleInertiaRequests::class,
],
创建控制器
php artisan make:controller HomeController

HomeController 内容如下。

namespace App\Http\Controllers;

use Inertia\Inertia;

class HomeController extends Controller
{
    public function index()
    {
        return Inertia::render('Home');
    }
}
创建页面

新增页面 resources/js/Pages/Home.vue

<template>
    <div>hello world</div>
</template>

<script>
export default {
    name: 'Home'
}
</script>
设置路由
use App\Http\Controllers\HomeController;

Route::get('/', [HomeController::class, 'index']);

客户端配置

安装前端依赖
npm install
安装必要的插件
安装 vue3
npm install vue@next
安装 inertia-vue3 适配器
npm install @inertiajs/inertia @inertiajs/inertia-vue3
安装 @vue/compiler-sfcvue-loader
npm install @vue/compiler-sfc vue-loader@^16.2.0 --save-dev --legacy-peer-deps
如果需要进度指示器,则安装 @inertiajs/progress
npm install @inertiajs/progress
修改 webpack.mix.js,添加 vue() 方法
mix.js('resources/js/app.js', 'public/js').vue()
    .postCss('resources/css/app.css', 'public/css', [
        //
    ]);
修改 resources/app.js
require('./bootstrap')

import { createApp, h } from 'vue'
import { createInertiaApp } from '@inertiajs/inertia-vue3'
import { InertiaProgress } from '@inertiajs/progress' // 如果需要进度指示器

InertiaProgress.init() // 如果需要进度指示器

createInertiaApp({
    resolve: name => require(`./Pages/${name}`),
    setup({ el, App, props, plugin }) {
        createApp({ render: () => h(App, props) })
            .use(plugin)
            .mount(el)
    },
})
执行编译
npm run dev

完美!经典的“hello world”可以正确地显示在浏览器上了。关于 laravel-mix 的使用方式,请参考官方文档

本作品采用《CC 协议》,转载必须注明作者和本文链接
不二
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 2

有没有 Vite 的版本。

2年前 评论
ztlcoder (楼主) 2年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!