【Vue.js入門到實(shí)戰(zhàn)教程】14-基于 Laravel Jetstream 的Vue 技術(shù)棧編寫表單組件
Laravel 8 引入 Jetstream 作為前端 UI 庫
在本月 8 號(hào),Laravel 8.0 正式發(fā)布,隨后 Vue 3.0?也正式發(fā)布,不過圍繞 Vue 3 生態(tài)的很多庫還處于 beta 階段,所以目前學(xué)院君這里的 Vue 實(shí)戰(zhàn)教程主要還是基于 Vue 2.x,不過后面會(huì)花幾個(gè)篇幅的教程簡(jiǎn)單介紹下 Vue 3 的新特性。
我們將基于 Laravel + Vue 框架進(jìn)行項(xiàng)目開發(fā),所以也需要關(guān)注下新版本 Laravel 框架前端組件技術(shù)棧相關(guān)的更新,這里需要注意的是 Laravel 8.0 引入了全新的 Jetstream 擴(kuò)展包提供前端 UI 腳手架代碼,如果你之前使用的是 laravel/ui 包(Laravel 6.0 引入)或者更早版本直接集成在新安裝 Laravel 項(xiàng)目中的前端腳手架代碼(Laravel 5.3 開始引入 Vue 作為默認(rèn)前端組件開發(fā)框架)開發(fā)前端 JavaScript 組件,同時(shí)使用 Laravel 默認(rèn)兼容的 Bootstrap CSS 框架,在 Laravel 8 中這些可能都將不再適用。
Jetstream 是一個(gè)為下一代 Laravel 項(xiàng)目全新設(shè)計(jì)的前端 UI 擴(kuò)展包,提供了基本的用戶認(rèn)證相關(guān)功能和必要的前端開發(fā)技術(shù)棧,只是這一次 Laravel 默認(rèn)選擇使用 Livewire + Blade 進(jìn)行前端組件開發(fā)(好處是不需要學(xué)習(xí) Vue、React 等前端框架,可以完全使用 PHP 代碼編寫頁面組件),同時(shí)默認(rèn)兼容的 CSS 框架也從 Bootstrap 切換到了 Tailwind。
當(dāng)然,Laravel 并不強(qiáng)制你使用這一套技術(shù)棧,所以 Jetstream 還提供了另一套基于 Inertia.js + Vue 開發(fā)前端組件的技術(shù)棧,這樣一來,你仍然可以用回之前可能已經(jīng)熟練掌握的 Vue 框架,對(duì)于 Tailwind 框架也是如此,你完全可以切換到其他 CSS 框架,只是 Laravel 官方提供的示例界面代碼可能需要重構(gòu),或者你完全可以選擇不使用 Jetstream,依然使用 laravel/ui 擴(kuò)展包,或者不用這些官方擴(kuò)展包,完全自行搭建前端技術(shù)棧。
Inertia 技術(shù)棧簡(jiǎn)介
使用 Inertia + Vue 編寫單頁面組件
初始化 Jetstream + Inertia
composer require laravel/jetstream
php artisan jetstream:install inertia
npm install && npm run dev
php artisan migrate

基于 Inertia 編寫 Vue 頁面組件
發(fā)布新文章這里是發(fā)布新文章頁面立即發(fā)布
<template><app-layout><template #header><h2 class="font-semibold text-xl text-gray-800 leading-tight">發(fā)布文章h2>template><div><div class="max-w-7xl mx-auto py-10 sm:px-6 lg:px-8"><post-create-form /><jet-section-border />div>div>app-layout>template><script>import AppLayout from './../../Layouts/AppLayout'import JetSectionBorder from './../../Jetstream/SectionBorder'import PostCreateForm from "./PostCreateForm";export default {components: {AppLayout,JetSectionBorder,PostCreateForm},}script>
編寫后端路由和控制器代碼
控制器方法
php artisan make:controller PostController
namespace App\Http\Controllers;use Illuminate\Http\Request;use Illuminate\Support\Facades\Validator;use Inertia\Inertia;class PostController extends Controller{// 渲染 Inertia 頁面組件public function create(Request $request){return Inertia::render('Post/Create');}// 處理表單組件提交的數(shù)據(jù)public function store(Request $request){Validator::make($request->all(), ['title' => ['required', 'max:255'],'author' => ['required'],'body' => ['required'],], ['required' => ':attribute 字段不能為空'])->validateWithBag('storePostInformation');// @todo 驗(yàn)證通過,保存文章數(shù)據(jù)...}}
注冊(cè)路由
use App\Http\Controllers\PostController;Route::group(['middleware' => config('jetstream.middleware', ['web'])], function () {Route::group(['middleware' => ['auth', 'verified']], function () {Route::get('/post/create', [PostController::class, 'create']);Route::post('/post', [PostController::class, 'store']);});});
使用 Vue 組件渲染頁面發(fā)布文章


小結(jié)

