Laravel 10.x - Inertiajs 使用 composer require tightenco/ziggy 组件

作者: 温新

分类: 【Laravel】

阅读: 1272

时间: 2023-03-26 08:13:16

hi,我是温新,一名 PHPer

tightenco/ziggy 该组件的作用是,可以在前端页面使用路由连接进行跳转。

第一步:安装组件
composer require tightenco/ziggy
第二步:注册组件
<!-- resources\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" />
    <!-- 使用 @routes 进行注册 -->
    @routes
    @vite('resources/js/app.js')
    @inertiaHead
</head>
<body>
@inertia
</body>
</html>
第三步:js 中绑定
// resources\js\app.js

import './bootstrap';

import { createApp, h } from 'vue'
import {createInertiaApp} from '@inertiajs/vue3'

createInertiaApp({
    resolve: name => {
        const pages = import.meta.glob('./Pages/**/*.vue', { eager: true })
        return pages[`./Pages/${name}.vue`]
    },
    setup({ el, App, props, plugin }) {
        createApp({ render: () => h(App, props) })
            .use(plugin)
            .mixin({methods: {route}}) // 绑定
            .mount(el)
    },
})
第四步:添加路由
<?php
// routes\web.php 
   
Route::get('/', function () {
    return inertia('Index');
})->name('index');

Route::get('about', function () {
    return inertia('About');
})->name('about');
第五步:添加 vue 页面

resources\js\Pages\Index.vue

<template>
    <Head>
        <title>首页</title>
    </Head>

    <Link :href="route('about')">关于我</Link>
    <hr>

    <h1>Home</h1>
</template>

<script>
    import route from "../../../vendor/tightenco/ziggy/src/js";

    export default {
        name: "Index",
        methods: {route}
    }
</script>

<style scoped>
</style>

resources\js\Pages\About.vue

<template>
    <Head>
        <title>关于我</title>
    </Head>
    <Link :href="route('index')">首页</Link>
    <hr>
    <h1>关于</h1>
</template>

<script setup>
</script>

<style scoped>
</style>
第六步:全局引入 Link、Head
// resources\js\app.js

import './bootstrap';

import { createApp, h } from 'vue'
import {createInertiaApp, Head, Link} from '@inertiajs/vue3'


createInertiaApp({
    resolve: name => {
        const pages = import.meta.glob('./Pages/**/*.vue', { eager: true })
        return pages[`./Pages/${name}.vue`]
    },
    setup({ el, App, props, plugin }) {
        createApp({ render: () => h(App, props) })
            .use(plugin)
            .mixin({methods: {route}}) // 绑定
            .component('Link', Link)
            .component('Head', Head)
            .mount(el)
    },
})
第七步:运行并测试
npm run dev
请登录后再评论