10分钟搭建NiceGUI电商界面:从产品展示到购物车全流程

【免费下载链接】nicegui Create web-based user interfaces with Python. The nice way. 【免费下载链接】nicegui 项目地址: https://gitcode.com/GitHub_Trending/ni/nicegui

你是否还在为Python构建交互式电商界面而烦恼?本文将带你使用NiceGUI框架快速实现一个完整的电商平台前端,包括响应式产品展示、动态购物车和即时库存管理。无需复杂的前端知识,仅需基础Python语法,即可在10分钟内完成搭建。

读完本文你将掌握:

  • 使用ui.gridui.card创建响应式产品布局
  • 通过数据绑定实现购物车动态更新
  • 结合ui.dialog实现商品详情弹窗
  • 利用ui.notification提供即时用户反馈

核心组件选择与项目结构

NiceGUI提供了丰富的UI组件库,特别适合快速构建电商界面。我们将重点使用以下组件:

项目基础结构建议参考示例目录组织:

examples/
├── e_commerce/           # 电商平台主目录
│   ├── main.py           # 应用入口
│   ├── products.py       # 产品数据管理
│   └── cart.py           # 购物车逻辑

实现响应式产品展示

产品展示是电商平台的核心,我们将使用ui.grid创建响应式布局,在不同设备上自动调整显示数量:

from nicegui import ui

# 产品数据模型
products = [
    {'id': 1, 'name': '无线耳机', 'price': 499, 'image': 'headphones.jpg', 'stock': 25},
    {'id': 2, 'name': '智能手表', 'price': 1299, 'image': 'watch.jpg', 'stock': 18},
    {'id': 3, 'name': '蓝牙音箱', 'price': 699, 'image': 'speaker.jpg', 'stock': 32},
    {'id': 4, 'name': '移动电源', 'price': 199, 'image': 'powerbank.jpg', 'stock': 45},
]

# 创建响应式网格布局
with ui.grid(columns=12).classes('w-full gap-4 p-4'):
    for product in products:
        # 每个产品占3列(大屏幕),6列(平板),12列(手机)
        with ui.card().classes('col-span-12 sm:col-span-6 md:col-span-4 lg:col-span-3'):
            with ui.column().classes('items-center'):
                # 产品图片
                ui.image(f'/static/products/{product["image"]}').classes('w-full h-48 object-cover')
                # 产品信息
                ui.label(product['name']).classes('text-lg font-bold mt-2')
                ui.label(f'¥{product["price"]}').classes('text-red-600 text-xl')
                # 库存状态
                stock_color = 'text-green-600' if product['stock'] > 10 else 'text-orange-600' if product['stock'] > 0 else 'text-red-600'
                ui.label(f'库存: {product["stock"]}').classes(f'{stock_color} text-sm')
                # 添加购物车按钮
                ui.button('加入购物车', on_click=lambda p=product: add_to_cart(p)) \
                    .classes('w-full mt-2') \
                    .props('color=primary')

上述代码通过ui.grid的响应式列设置,实现了在不同屏幕尺寸下自动调整每行显示的产品数量。每个产品卡片使用ui.card容器,内部包含图片、名称、价格和操作按钮。

构建动态购物车系统

购物车功能需要实现添加商品、更新数量和计算总价等核心功能。我们将使用NiceGUI的数据绑定功能实现状态自动同步:

from nicegui import ui
from dataclasses import dataclass, field
from typing import List

@dataclass
class CartItem:
    product_id: int
    name: str
    price: int
    quantity: int = 1
    total: int = field(init=False)
    
    def __post_init__(self):
        self.total = self.price * self.quantity

# 购物车状态管理
cart_items = ui.reactive([])
total_price = ui.reactive(0)

def add_to_cart(product):
    # 检查商品是否已在购物车
    for item in cart_items.value:
        if item.product_id == product['id']:
            item.quantity += 1
            item.total = item.price * item.quantity
            cart_items.refresh()
            ui.notification(f'已更新 {product["name"]} 数量至 {item.quantity}')
            return
    
    # 添加新商品到购物车
    new_item = CartItem(
        product_id=product['id'],
        name=product['name'],
        price=product['price']
    )
    cart_items.value.append(new_item)
    ui.notification(f'已添加 {product["name"]} 到购物车')
    cart_items.refresh()

# 购物车侧边栏
with ui.right_drawer(title='我的购物车', value=False) as cart_drawer:
    with ui.column().classes('w-full'):
        ui.label('购物车').classes('text-xl font-bold mb-4')
        
        @ui.refreshable
        def cart_content():
            if not cart_items.value:
                ui.label('购物车为空').classes('text-center my-8')
                return
                
            # 购物车列表
            with ui.scroll_area().classes('h-64'):
                for item in cart_items.value:
                    with ui.row().classes('items-center justify-between w-full mb-2'):
                        ui.label(f'{item.name} (¥{item.price})')
                        with ui.row().classes('items-center'):
                            ui.button('-', on_click=lambda i=item: update_quantity(i, -1)) \
                                .props('flat square size=sm')
                            ui.label(str(item.quantity)).classes('w-8 text-center')
                            ui.button('+', on_click=lambda i=item: update_quantity(i, 1)) \
                                .props('flat square size=sm')
                            ui.label(f'¥{item.total}').classes('w-16 text-right')
            
            # 总计
            total = sum(item.total for item in cart_items.value)
            ui.separator().classes('my-4')
            with ui.row().classes('justify-between items-center font-bold text-lg'):
                ui.label('总计:')
                ui.label(f'¥{total}')
            
            # 结算按钮
            ui.button('结算', on_click=lambda: ui.navigate.to('/checkout')) \
                .classes('w-full mt-4') \
                .props('color=primary')

        cart_content()
        
        # 监听购物车变化自动刷新
        cart_items.on_change(cart_content.refresh)

# 顶部导航栏购物车按钮
with ui.header().classes('justify-between'):
    ui.label('NiceGUI电商平台').classes('text-xl font-bold')
    with ui.row().classes('items-center'):
        ui.button(icon='shopping_cart', on_click=cart_drawer.toggle) \
            .props('flat color=primary')

这段代码实现了完整的购物车功能,包括:

  • 使用ui.reactive创建响应式购物车状态
  • 通过cart_items.on_change实现内容自动刷新
  • 支持商品数量调整和总价实时计算
  • 右侧抽屉式购物车界面

商品详情与库存管理

为提升用户体验,我们添加商品详情弹窗和库存管理功能:

def show_product_detail(product):
    with ui.dialog() as dialog, ui.card().classes('w-full max-w-2xl'):
        with ui.row().classes('w-full'):
            # 商品图片
            with ui.column().classes('w-1/2'):
                ui.image(f'/static/products/{product["image"]}').classes('w-full h-full object-contain')
            
            # 商品详情
            with ui.column().classes('w-1/2 p-4'):
                ui.label(product['name']).classes('text-2xl font-bold')
                ui.label(f'¥{product["price"]}').classes('text-red-600 text-3xl mt-2')
                
                ui.separator().classes('my-4')
                
                ui.label('商品描述').classes('text-lg font-semibold')
                ui.markdown('''
                    高品质产品,采用最新技术制造,
                    提供卓越的用户体验和长久的使用寿命。
                    官方正品保障,全国联保一年。
                ''').classes('mt-2')
                
                ui.separator().classes('my-4')
                
                # 数量选择
                with ui.row().classes('items-center mt-4'):
                    ui.label('购买数量:')
                    quantity = ui.number(value=1, min=1, max=product['stock']).classes('ml-2 w-20')
                
                # 操作按钮
                with ui.row().classes('mt-6 gap-2'):
                    ui.button('加入购物车', on_click=lambda: [
                        add_to_cart({**product, 'quantity': quantity.value}),
                        dialog.close()
                    ]).props('color=primary')
                    ui.button('立即购买', on_click=lambda: [
                        add_to_cart({**product, 'quantity': quantity.value}),
                        dialog.close(),
                        cart_drawer.toggle()
                    ]).props('color=secondary')

# 修改产品卡片添加点击事件
ui.card().on_click(lambda: show_product_detail(product))

这段代码通过ui.dialog实现了商品详情弹窗,用户可以查看完整信息并选择购买数量。同时增加了库存限制,防止超卖。

完整集成与运行

将上述功能整合到主应用中,完整代码结构如下:

# main.py
from nicegui import ui
from dataclasses import dataclass, field
from typing import List

# [此处省略产品数据和CartItem定义]

def main():
    # 设置页面标题和样式
    ui.page_title('NiceGUI电商平台')
    ui.add_head_html('<link rel="stylesheet" href="https://cdn.tailwindcss.com">')
    
    # 创建产品展示区
    # [此处省略产品网格布局代码]
    
    # 创建购物车功能
    # [此处省略购物车相关代码]
    
    # 创建商品详情弹窗
    # [此处省略商品详情代码]
    
    # 启动应用
    ui.run(title='NiceGUI电商平台', port=8080)

if __name__ == '__main__':
    main()

运行应用前,需要准备产品图片并放置在static/products目录下。然后执行以下命令启动:

python main.py

功能扩展与优化建议

NiceGUI电商界面可以通过以下方式进一步增强:

  1. 用户认证:集成examples/authentication/示例实现用户登录
  2. 支付集成:添加examples/stripe/实现支付功能
  3. 订单管理:参考examples/sqlite_database/实现订单存储
  4. 搜索功能:使用examples/search_as_you_type/实现实时搜索

总结

本文展示了如何使用NiceGUI快速构建电商平台的核心功能,包括响应式产品展示、动态购物车和商品详情交互。通过数据绑定和组件化设计,我们实现了一个功能完整且用户友好的电商界面。

NiceGUI的优势在于:

  • 纯Python开发,无需前端知识
  • 丰富的内置组件,满足电商需求
  • 响应式设计,适配各种设备
  • 简洁的API,提高开发效率

完整代码可参考examples/e_commerce/目录结构实现。现在你可以基于这个框架继续扩展功能,打造属于自己的电商平台了!

【免费下载链接】nicegui Create web-based user interfaces with Python. The nice way. 【免费下载链接】nicegui 项目地址: https://gitcode.com/GitHub_Trending/ni/nicegui

Logo

电商企业物流数字化转型必备!快递鸟 API 接口,72 小时快速完成物流系统集成。全流程实战1V1指导,营造开放的API技术生态圈。

更多推荐