MST

星途 面试题库

面试题:Qwik路由中如何处理动态路由参数及实现页面间数据传递

在Qwik应用里,有一个商品详情页面`ProductDetailPage`,其路由需要根据商品ID动态生成,例如`/product/:productId`。当用户从商品列表页面点击进入详情页时,如何在路由跳转过程中传递商品的其他信息(如商品名称、价格等)到`ProductDetailPage`组件,并在`ProductDetailPage`中获取并展示这些数据?请阐述详细的实现思路及关键代码。
32.7万 热度难度
前端开发Qwik

知识考点

AI 面试

面试题答案

一键面试
  1. 实现思路
    • 在商品列表页面,当点击商品进入详情页时,通过在跳转链接中附加商品其他信息作为查询参数的方式传递数据。
    • ProductDetailPage组件中,使用Qwik提供的路由相关函数来获取这些查询参数并展示数据。
  2. 关键代码
    • 商品列表页面:假设使用@builder.io/qwik库,且商品列表项渲染代码如下:
import { component$, useNavigate } from '@builder.io/qwik';
import type { Product } from './types';

export const ProductListItem = component$(({ product }: { product: Product }) => {
    const navigate = useNavigate();
    return (
        <div onClick={() => {
            navigate(`/product/${product.id}?name=${encodeURIComponent(product.name)}&price=${product.price}`);
        }}>
            {/* 商品列表项展示内容 */}
            <p>{product.name}</p>
        </div>
    );
});
  • ProductDetailPage组件
import { component$, useRouteLoaderData } from '@builder.io/qwik';

export const ProductDetailPage = component$(() => {
    const { data } = useRouteLoaderData();
    const name = data.get('name') && decodeURIComponent(data.get('name') as string);
    const price = data.get('price') && parseFloat(data.get('price') as string);
    return (
        <div>
            <h1>{name}</h1>
            <p>价格: {price}</p>
        </div>
    );
});

上述代码中,在商品列表页面通过navigate函数跳转到商品详情页路由,并将商品名称和价格作为查询参数附加在URL中。在ProductDetailPage组件中,使用useRouteLoaderData获取路由数据,进而提取并展示商品名称和价格。