您现在的位置是:自如初>LaravelLaravel

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

温新 2023-03-26 16:13:16 Laravel 259人已围观

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

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

很赞哦!(5)

文章评论

登录 注册

  • bob    2023年04月14日

    老板,第三步的route未定义呀

自如初--时间轴

站名:自如初

独白:向前走!向前走!

邮箱:ziruchu@qq.com

RSS: RSS

站点信息