laravel框架中安装inertia.js + vue3版本的流程步骤

2023-06-01 框架 步骤 流程

Inertia 是一种新的构建经典的服务端驱动的 web 应用的方法。我们称之为现代 monolith。

inertia 允许你创建完整的客户端渲染单页面程序,以及没有复杂工具链的现代 SPAs 应用。它通过现有的服务端框架来完成这一切。

Inertia 没有客户端的路由,也不需要 API。你只需要和往常一样编写控制器和页面视图。

官方手册:

https://inertia.zhitiantu.com/zh/introduction.html

准备工作

laravel框架
Node JS
Npm 包管理工具


服务端配置

依赖包安装

composer require inertiajs/inertia-laravel

laravel 目录 resouces/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>

执行 artisan 命令,添加中间件

php artisan inertia:middleware

文件生成后,手动添加到 Kernel 文件中的 web 中间件组最后一行

'web' => [
    // ...
    \App\Http\Middleware\HandleInertiaRequests::class,
],


客户端配置

使用 npm 命令安装前端框架依赖,安装 VUE3 版本

npm install @inertiajs/inertia @inertiajs/inertia-vue3

初始化应用

打开 /resouces/js/app.js,清空后覆盖以下代码

import { createApp, h } from 'vue'
import { createInertiaApp } from '@inertiajs/inertia-vue3'
createInertiaApp({
  resolve: name => require(`./Pages/${name}`),
  setup({ el, app, props, plugin }) {
    createApp({ render: () => h(app, props) })
      .use(plugin)
      .mount(el)
  },
})

npm 安装进度条包

使用 inertia 做出来的页面,浏览器不会刷新,为了用户感知增加了页面顶部进度条这种友好的提示

npm install @inertiajs/progress

安装完成后,引入并初始化,打开 /resouces/js/app.js,清空后覆盖以下代码

import { createApp, h } from 'vue'
import { createInertiaApp } from '@inertiajs/inertia-vue3'
import { InertiaProgress } from '@inertiajs/progress'
createInertiaApp({
    resolve: name => import(`./Pages/${name}`),
    setup({ el, app, props, plugin }) {
        createApp({ render: () => h(app, props) })
            .use(plugin)
            .mount(el)
    },
})
InertiaProgress.init()

使用以下 webpack 配置来强制浏览器在文件更新后,加载新的资源,而不是使用缓存。

打开 webpack.mix.js,清空并覆盖以下代码

const mix = require('laravel-mix');
mix.js('resources/js/app.js', 'public/js')
    .postCss('resources/css/app.css', 'public/css', [
        //
    ]);
mix.webpackConfig({
    output: {
        chunkFilename: 'js/[name].js?id=[chunkhash]',
    }
});


安装 VUE

使用 npm 命令安装 vue 最新稳定版

npm install [email protected]

添加.vue () 到 webpack.mix.js

const mix = require('laravel-mix');
mix.js('resources/js/app.js', 'public/js')
    .vue()
    .postCss('resources/css/app.css', 'public/css', [
        //
    ]);
mix.webpackConfig({
    output: {
        chunkFilename: 'js/[name].js?id=[chunkhash]',
    }
});

通过 npm 命令运行

npm run watch

安装中遇到错误及解决方式

1.

Error: Cannot find module 'webpack/lib/rules/DescriptionDataMatcherRulePlugin'

解决方式:升级vue-loader

npm i vue-loader


2.

ERROR in ./resources/js/app.js 6:11-42
Module not found;Error;Can't resolve './Pages' in ...

解决方式:resouces/js目录下新增Pages文件夹。


相关文章