livewireshopping / livewire-shopping-cart
使用 Livewire 的 Laravel 电子商务包
v1.0.0
2024-05-20 02:02 UTC
Requires
- php: ^7.3|^8.0
- laravel/framework: ^11.0
- livewire/livewire: ^3.0
README
这是一个用于动态电子商务购物车系统的 Laravel 包,使用 Livewire。无需重新加载页面即可添加、删除和显示购物车总额。
安装
您可以通过 Composer 安装此包
composer require livewireshopping/livewire-shopping-cart
配置
php artisan vendor:publish --provider="LivewireShopping\LivewireShoppingCart\CartServiceProvider" --tag="config" This will create a cart.php file in the config folder where you can modify the cart settings.
将产品添加到购物车
Create a Livewire component `AddToCart`: Modify the AddToCart component:
<?php namespace App\Http\Livewire; use Livewire\Component; use Cart; class AddToCart extends Component { public $product; public function addToCart($product) { Cart::add($product); $this->emit('cartUpdated'); } public function render() { return view('livewire.add-to-cart'); } }
创建 add-to-cart.blade.php 组件的视图
<!-- resources/views/livewire/add-to-cart.blade.php --> <button wire:click="addToCart({{ $product->id }})">Add to Cart</button>
显示购物车总额
创建 Livewire 组件 CartTotal
php artisan make:livewire CartTotal <?php namespace App\Http\Livewire; use Livewire\Component; use Cart; class CartTotal extends Component { protected $listeners = ['cartUpdated' => 'updateTotal']; public $total; public function mount() { $this->total = Cart::total(); } public function updateTotal() { $this->total = Cart::total(); } public function render() { return view('livewire.cart-total'); } } Create the view for the cart-total.blade.php component: <!-- resources/views/livewire/cart-total.blade.php --> <div> Total: ${{ $total }} </div> Use the Components in the Main View <!-- resources/views/shop.blade.php --> @extends('layouts.app') @section('content') <div> @foreach($products as $product) <div> <h3>{{ $product->name }}</h3> <livewire:add-to-cart :product="$product" /> </div> @endforeach </div> <div> <livewire:cart-total /> </div> @endsection
其他配置
composer require livewire/livewire <!-- resources/views/layouts/app.blade.php --> <!DOCTYPE html> <html lang="en"> <head> <!-- ... --> @livewireStyles </head> <body> <!-- ... --> @livewireScripts </body> </html>
贡献
贡献
欢迎贡献!请按照以下步骤进行贡献
- 将仓库分叉。
- 创建一个新的分支(
git checkout -b feature-branch
)。 - 进行更改并提交(
git commit -m '添加新功能'
)。 - 将更改推送到分支(
git push origin feature-branch
)。 - 提交一个 Pull Request。
请确保所有新功能都包括测试和文档。
许可证
8. 更新 composer.json
{ "name": "vendor/livewire-shopping-cart", "description": "A Laravel e-commerce package with Livewire", "require": { "php": "^7.3|^8.0", "livewire/livewire": "^2.0", "laravel/framework": "^11.0" }, "autoload": { "psr-4": { "Vendor\\LivewireShoppingCart\\": "src/" } }, "extra": { "laravel": { "providers": ["Vendor\\LivewireShoppingCart\\CartServiceProvider"], "aliases": { "Cart": "Vendor\\LivewireShoppingCart\\CartFacade" } } } }