Laravel 11 和 Vue.js:安裝、設定和範例
Laravel 11 和 vue.js 是編寫簡潔高效程式碼的絕佳組合。
在本教程中,我們將一起了解如何使用 vue.js 的強大功能在 Laravel 11 中安裝、設定和開發。
為了測試 vue.js,我們將編寫程式碼來管理「部落格文章」資料實體。
6 minuti
本文所述的範例是 Laravel 設定教學 vue.js 的範例,可以在 Github上.
安裝 vue.js
我們將設定 Laravel 11 框架,安裝 Vue.js JavaScript 框架,並使其與 Vite 一起使用。然後我們將載入第一個 Vue 元件。
composer create-project --prefer-dist laravel/laravel crud-spa
我們來配置一下詳細信息 數據庫:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=<DATABASE NAME>
DB_USERNAME=<DATABASE USERNAME>
DB_PASSWORD=<DATABASE PASSWORD>
安裝 Laravel 後,讓我們繼續安裝 Laravel Breeze。
您不需要 Breeze 來使用 vue.js。這只是個人喜好:我們不會將它用於身份驗證系統,也不會使用它的 vue 版本,它只是為了快速簡便的視覺設計,因此我們將刪除它的許多部分。
composer require laravel/breeze --dev
php artisan breeze:install blade
為簡單起見,我們只為儀表板建立一個公開頁面,然後從呼叫身份驗證的導覽中刪除所有連結。在桌面和行動選單中。
文件 resources/views/layouts/navigation.blade.php
變成:
<nav x-data="{ open: false }" class="bg-white border-b border-gray-100">
<!-- Primary Navigation Menu -->
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex justify-between h-16">
<div class="flex">
<!-- Logo -->
<div class="shrink-0 flex items-center">
<a href="{{ route('dashboard') }}">
<x-application-logo class="block h-9 w-auto fill-current text-gray-800" />
</a>
</div>
<!-- Navigation Links -->
<div class="hidden space-x-8 sm:-my-px sm:ms-10 sm:flex">
<x-nav-link :href="route('dashboard')" :active="request()->routeIs('dashboard')">
{{ __('Dashboard') }}
</x-nav-link>
</div>
</div>
<!-- Hamburger -->
<div class="-me-2 flex items-center sm:hidden">
<button @click="open = ! open" class="inline-flex items-center justify-center p-2 rounded-md text-gray-400 hover:text-gray-500 hover:bg-gray-100 focus:outline-none focus:bg-gray-100 focus:text-gray-500 transition duration-150 ease-in-out">
<svg class="h-6 w-6" stroke="currentColor" fill="none" viewBox="0 0 24 24">
<path :class="{'hidden': open, 'inline-flex': ! open }" class="inline-flex" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" />
<path :class="{'hidden': ! open, 'inline-flex': open }" class="hidden" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
</div>
</div>
<!-- Responsive Navigation Menu -->
<div :class="{'block': open, 'hidden': ! open}" class="hidden sm:hidden">
<div class="pt-2 pb-3 space-y-1">
<x-responsive-nav-link :href="route('dashboard')" :active="request()->routeIs('dashboard')">
{{ __('Dashboard') }}
</x-responsive-nav-link>
</div>
</div>
</nav>
在路由檔案中 web.php
,我們只需要一條到索引頁的路由,而且它只能是一個視圖。路由的 CRUD 將使用 vue-router
.
文件 routes/web.php
變成:
<?php
use App\Http\Controllers\ProfileController;
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('dashboard');
})->name('dashboard');
現在我們需要指定 Vue 何時被「掛載」。也就是說,HTML 結構的主要元素,Vue 將駐留在「其中」。通常,它是主佈局中的主要 div 元素之一,為了識別它,我們分配它 id=”app」。
那麼讓我們打開文件 資源/視圖/版面/app.blade.php 並在開啟 body 後的第一個 div 中新增屬性:
.
.
.
<!-- Fonts -->
<link rel="preconnect" href="https://fonts.bunny.net">
<link href="https://fonts.bunny.net/css?family=figtree:400,500,600&display=swap" rel="stylesheet" />
<!-- Scripts -->
@vite(['resources/css/app.css', 'resources/js/app.js'])
</head>
<body class="font-sans antialiased">
<div class="min-h-screen bg-gray-100" id="app">
@include('layouts.navigation')
<!-- Page Heading -->
@isset($header)
<header class="bg-white shadow">
<div class="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
{{ $header }}
</div>
</header>
@endisset
.
.
.
Laravel vue.js 配置教程
預設情況下,Breeze 新增了 Alpine.js,但我們不會使用它。因此,我們修改 Laravel 根目錄中的 package.json,並刪除 Alpine.js。
在本節中 devDependencies
package.json 中,我們刪除該行
{
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build"
},
"devDependencies": {
"@tailwindcss/forms": "^0.5.2",
"alpinejs": "^3.4.2",
"autoprefixer": "^10.4.2",
"axios": "^1.6.4",
"laravel-vite-plugin": "^1.0",
"postcss": "^8.4.31",
"tailwindcss": "^3.1.0",
"vite": "^5.0"
}
}
現在我們可以安裝 Vue 和 Vue loader 並設定 Vue。
npm install vue vue-loader
接下來,我們需要安裝Vue Vite插件。
npm install --save-dev @vitejs/plugin-vue
讓我們編輯該文件 vite.config.js
存在於 laravel root 中,如下:
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue';
export default defineConfig({
plugins: [
laravel({
input: [
'resources/css/app.css',
'resources/js/app.js',
],
refresh: true,
}),
vue({
template: {
transformAssetUrls: {
base: null,
includeAbsolute: false,
},
},
}),
],
resolve: {
alias: {
vue: 'vue/dist/vue.esm-bundler.js',
},
},
});
Vue元件創建
我們在 Dashboard 頁面上新增一個 vue 元件。將來它將顯示帖子列表,因此我們將調用它的 HTML 標籤。
我們來編輯文件 資源/視圖/dashboard.blade.php 如下:
<x-app-layout>
<x-slot name="header">
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
{{ __('Dashboard') }}
</h2>
</x-slot>
<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">
{{ __("You're logged in!") }}
<posts-index></posts-index>
</div>
</div>
</div>
</div>
</x-app-layout>
更換 {{ __("You're logged in!") }}
同 <posts-index></posts-index>
.
現在讓我們繼續建立 Vue 元件 資源/js/components/Posts/Index.vue。現在我們只會在其中插入虛擬靜態文字。
我們來編輯文件 資源/js/components/Posts/Index.vue:
<template>
Table coming soon.
</template>
每個 Vue 組件由兩個部分組成:
<script>
<template>
在本例中,我們還沒有執行任何 JS 操作,因此我們不會有腳本部分,只有 template
.
現在,回到元素 id="app"
,讓我們繼續初始化一個 Vue 應用程序,添加上面的元件,並將其安裝到該應用程式元素。這一切都需要在主文件中完成 resources/js/app.js
。預設情況下,Breeze 的 app.js 檔案包含使用 Alpine.js 的程式碼,根據實作選擇,我們將其刪除。
文件 資源/js/app.js 變成:
import './bootstrap';
import { createApp } from 'vue'
import PostsIndex from './components/Posts/Index.vue'
createApp({})
.component('PostsIndex', PostsIndex)
.mount('#app')
在 app.js 檔案中,我們定義 Vue 應用程式 createApp()
,預先導入我們將一個元件附加到Vue應用程序,預先導入它並給它命名 PostIndex
.
讓我們在專案上安裝 Vue 應用程式 #app
從主佈局來看。
這就是我們命名組件的方式 PostIndex
所以你知道它是帖子的一個組件,它是一個文件 Index.vue
.
呼叫Vue檔案中的元件有兩種方式:
- 我們使用的是
kebab-used
. - 其次,使用
PascalCase
.
Vue.js 支援這兩種情況。因此,對於元件命名,我們使用 PascalCase。
現在讓我們使用以下命令來編譯所有內容 npm run dev
o npm run build
,完成後,在瀏覽器中打開頁面,我們應該看到文本 Table coming Soon
, 如下:
JS 和 Tailwind 重新編譯
當使用任何前端檔案時,我們需要在每次更改後重新編譯以在瀏覽器中看到更改。因此我們必須執行 npm run build
每次進行小更改後,或者更好地運行 npm run dev 並使其在背景運行。
當我們執行 npm run dev
使用Vite,每次重新編譯後瀏覽器都會自動更新。運行後 npm run dev
在您的控制台中,您將看到類似以下內容的結果:
DOPO npm run build
在影片中我們將看到:
例子
現在讓我們嘗試在 Vue 檔案中進行簡單的修改:讓我們為元件新增一個簡單的靜態表(暫時) PostIndex Vue
.
所描述的範例可在 Github上.
然後是文件 resources/js/components/Posts/Index.vue
變成:
<template>
<div class="overflow-hidden overflow-x-auto p-6 bg-white border-gray-200">
<div class="min-w-full align-middle">
<table class="min-w-full divide-y divide-gray-200 border">
<thead>
<tr>
<th class="px-6 py-3 bg-gray-50 text-left">
<span class="text-xs leading-4 font-medium text-gray-500 uppercase tracking-wider">ID</span>
</th>
<th class="px-6 py-3 bg-gray-50 text-left">
<span class="text-xs leading-4 font-medium text-gray-500 uppercase tracking-wider">Title</span>
</th>
<th class="px-6 py-3 bg-gray-50 text-left">
<span class="text-xs leading-4 font-medium text-gray-500 uppercase tracking-wider">Content</span>
</th>
<th class="px-6 py-3 bg-gray-50 text-left">
<span class="text-xs leading-4 font-medium text-gray-500 uppercase tracking-wider">Created at</span>
</th>
</tr>
</thead>
<tbody class="bg-white divide-y divide-gray-200 divide-solid">
<tr>
<td class="px-6 py-4 whitespace-no-wrap text-sm leading-5 text-gray-900">1</td>
<td class="px-6 py-4 whitespace-no-wrap text-sm leading-5 text-gray-900">A</td>
<td class="px-6 py-4 whitespace-no-wrap text-sm leading-5 text-gray-900">Poe switched his focus to prose, and spent the next several years working for literary journals and periodicals, becoming known for his own style of literary criticism. His work forced him to move between several cities, including Baltimore, Philadelphia, and New York City. In 1836, when he was 27, he married his 13-year-old cousin, Virginia Clemm. She died of tuberculosis in 1847. In January 1845, he published his poem "The Raven" to instant success. He planned for years to produce his own journal The Penn, later renamed The Stylus. But before it began publishing, Poe died in Baltimore in 1849, aged 40, under mysterious circumstances. The cause of his death remains unknown, and has been variously attributed to many causes including disease, alcoholism, substance abuse, and suicide.</td>
<td class="px-6 py-4 whitespace-no-wrap text-sm leading-5 text-gray-900">2024-06-01 13:43:47</td>
</tr>
<tr>
<td class="px-6 py-4 whitespace-no-wrap text-sm leading-5 text-gray-900">2</td>
<td class="px-6 py-4 whitespace-no-wrap text-sm leading-5 text-gray-900">B</td>
<td class="px-6 py-4 whitespace-no-wrap text-sm leading-5 text-gray-900">Poe switched his focus to prose, and spent the next several years working for literary journals and periodicals, becoming known for his own style of literary criticism. His work forced him to move between several cities, including Baltimore, Philadelphia, and New York City. In 1836, when he was 27, he married his 13-year-old cousin, Virginia Clemm. She died of tuberculosis in 1847. In January 1845, he published his poem "The Raven" to instant success. He planned for years to produce his own journal The Penn, later renamed The Stylus. But before it began publishing, Poe died in Baltimore in 1849, aged 40, under mysterious circumstances. The cause of his death remains unknown, and has been variously attributed to many causes including disease, alcoholism, substance abuse, and suicide.</td>
<td class="px-6 py-4 whitespace-no-wrap text-sm leading-5 text-gray-900">2024-06-02 14:43:47</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
但現在 Tailwind 遇到了一個問題:它不接受我們新增的 CSS 樣式。我們需要將Vue元件的位置加入到Tailwind設定檔中,以便它自動收集並編譯Vue中使用的類別。
我們來編輯文件 tailwind.config.js:
import defaultTheme from 'tailwindcss/defaultTheme';
import forms from '@tailwindcss/forms';
/** @type {import('tailwindcss').Config} */
export default {
content: [
'./vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php',
'./storage/framework/views/*.php',
'./resources/views/**/*.blade.php',
'./resources/js/components/**/*.vue',
],
theme: {
extend: {
fontFamily: {
sans: ['Figtree', ...defaultTheme.fontFamily.sans],
},
},
},
plugins: [forms],
};