laravel怎么安装inertia vue3的版本

发布时间:2023-03-16 15:04:02 作者:iii
来源:亿速云 阅读:194
# Laravel怎么安装Inertia Vue3的版本

## 前言

Inertia.js是一个创新的前端框架,它允许开发者使用Vue、React或Svelte等现代前端框架构建单页面应用(SPA),同时保持传统的服务端渲染(SSR)工作流程。本文将详细介绍如何在Laravel项目中安装和配置Inertia.js与Vue3的组合。

## 环境准备

在开始之前,请确保你的开发环境满足以下要求:

- PHP >= 8.0
- Laravel >= 9.x
- Node.js >= 16.x
- Composer 最新版本
- NPM/Yarn 最新版本

## 第一步:创建新的Laravel项目

如果你还没有Laravel项目,可以通过以下命令创建一个:

```bash
composer create-project laravel/laravel inertia-vue3-demo
cd inertia-vue3-demo

第二步:安装Inertia服务端适配器

Inertia需要服务端和客户端适配器。首先安装Laravel的服务端适配器:

composer require inertiajs/inertia-laravel

第三步:设置根模板

Inertia需要一个根模板文件来加载你的JavaScript应用。创建resources/views/app.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title inertia>{{ config('app.name', 'Laravel') }}</title>
    
    <!-- Scripts -->
    @routes
    @vite(['resources/js/app.js', "resources/js/Pages/{$page['component']}.vue"])
    @inertiaHead
</head>
<body class="font-sans antialiased">
    @inertia
</body>
</html>

第四步:创建中间件

生成Inertia中间件:

php artisan inertia:middleware

然后在app/Http/Kernel.php中注册这个中间件:

protected $middlewareGroups = [
    'web' => [
        // 其他中间件...
        \App\Http\Middleware\HandleInertiaRequests::class,
    ],
];

第五步:安装客户端依赖

现在安装Vue3和Inertia客户端适配器:

npm install @inertiajs/vue3 vue@next @vitejs/plugin-vue

第六步:配置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/js/app.js',
            refresh: true,
        }),
        vue({
            template: {
                transformAssetUrls: {
                    base: null,
                    includeAbsolute: false,
                },
            },
        }),
    ],
});

第七步:初始化Inertia应用

修改resources/js/app.js

import { createApp, h } from 'vue'
import { createInertiaApp } from '@inertiajs/vue3'
import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers'

createInertiaApp({
    resolve: (name) => resolvePageComponent(`./Pages/${name}.vue`, import.meta.glob('./Pages/**/*.vue')),
    setup({ el, App, props, plugin }) {
        createApp({ render: () => h(App, props) })
            .use(plugin)
            .mount(el)
    },
})

第八步:创建第一个页面

创建resources/js/Pages/Welcome.vue

<script setup>
import { Head, Link } from '@inertiajs/vue3'
</script>

<template>
    <Head title="Welcome" />
    
    <div class="min-h-screen bg-gray-100">
        <div class="py-12">
            <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
                <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                    <div class="p-6 text-gray-900">
                        <h1 class="text-2xl font-bold mb-4">Welcome to Inertia + Vue3!</h1>
                        <Link href="/about" class="text-blue-500 hover:underline">About Page</Link>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

第九步:设置路由

修改routes/web.php

<?php

use Illuminate\Support\Facades\Route;
use Inertia\Inertia;

Route::get('/', function () {
    return Inertia::render('Welcome');
});

Route::get('/about', function () {
    return Inertia::render('About');
});

第十步:创建About页面

创建resources/js/Pages/About.vue

<script setup>
import { Head, Link } from '@inertiajs/vue3'
</script>

<template>
    <Head title="About" />
    
    <div class="min-h-screen bg-gray-100">
        <div class="py-12">
            <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
                <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                    <div class="p-6 text-gray-900">
                        <h1 class="text-2xl font-bold mb-4">About Page</h1>
                        <Link href="/" class="text-blue-500 hover:underline">Back to Home</Link>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

第十一步:添加共享数据

app/Http/Middleware/HandleInertiaRequests.php中,你可以添加共享数据:

public function share(Request $request)
{
    return array_merge(parent::share($request), [
        'auth' => [
            'user' => $request->user(),
        ],
        'flash' => [
            'message' => fn () => $request->session()->get('message')
        ],
    ]);
}

第十二步:运行开发服务器

现在可以启动开发服务器了:

npm run dev
php artisan serve

访问http://localhost:8000应该能看到你的Inertia + Vue3应用了!

常见问题解决

1. 组件未正确解析

确保你的Vite配置正确,特别是resolvePageComponent函数的使用。检查文件路径是否正确。

2. 样式未加载

如果你使用Tailwind CSS或其他CSS框架,确保在app.js中正确导入:

import '../css/app.css'

3. 热更新不工作

检查Vite配置中的refresh选项是否启用,并确保端口没有被占用。

高级配置

使用Pinia状态管理

安装Pinia:

npm install pinia

然后在app.js中设置:

import { createPinia } from 'pinia'

const pinia = createPinia()
createApp({ render: () => h(App, props) })
    .use(plugin)
    .use(pinia)
    .mount(el)

添加路由过渡效果

安装@headlessui/vue@heroicons/vue

npm install @headlessui/vue @heroicons/vue

然后在布局组件中添加过渡:

<template>
    <Transition
        enter-active-class="transition duration-300"
        enter-from-class="opacity-0"
        enter-to-class="opacity-100"
        leave-active-class="transition duration-300"
        leave-from-class="opacity-100"
        leave-to-class="opacity-0"
    >
        <component :is="Component" />
    </Transition>
</template>

部署到生产环境

  1. 构建前端资源:
npm run build
  1. 优化Composer自动加载:
composer install --optimize-autoloader --no-dev
  1. 缓存路由和配置:
php artisan config:cache
php artisan route:cache

结论

通过以上步骤,你已经成功在Laravel项目中集成了Inertia.js和Vue3。这种组合提供了现代SPA的开发体验,同时保持了Laravel强大的后端功能。Inertia的简单性和Vue3的组合式API使得开发复杂的单页应用变得更加高效。

进一步学习

”`

这篇文章详细介绍了从零开始安装和配置Inertia.js与Vue3的完整过程,涵盖了从基础设置到高级配置的各个方面,并提供了常见问题的解决方案。

推荐阅读:
  1. 安装 Laravel 框架
  2. composer如何安装laravel指定版本

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

laravel vue3

上一篇:thinkphp5.0.x命令是怎么执行filter的

下一篇:从H5页面跳转到小程序的实现方案有哪些

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》