面试题答案
一键面试路由路径设计
- 首页展示所有产品类别:
/products
- 展示某个类别下所有子类别及产品:
/products/:category
- 展示某个子类别下的产品:
/products/:category/:sub - category
- 产品详情页:
/products/:category/:sub - category/:productId
代码示例(基于Qwik框架)
- 创建路由配置文件(假设为
routes.ts
)
import { createRoutes } from '@builder.io/qwik-city';
export const routes = createRoutes(() => {
return [
{
path: '/products',
component: async () => import('./components/ProductCategoriesPage.tsx')
},
{
path: '/products/:category',
component: async () => import('./components/ProductsByCategoryPage.tsx')
},
{
path: '/products/:category/:sub - category',
component: async () => import('./components/ProductsBySubCategoryPage.tsx')
},
{
path: '/products/:category/:sub - category/:productId',
component: async () => import('./components/ProductDetailPage.tsx')
}
];
});
- 示例页面组件(以
ProductDetailPage.tsx
为例)
import { component$, useRouteParams } from '@builder.io/qwik';
export default component$(() => {
const { category, 'sub - category': subCategory, productId } = useRouteParams();
return (
<div>
<h1>Product Detail</h1>
<p>Category: {category}</p>
<p>Sub - Category: {subCategory}</p>
<p>Product ID: {productId}</p>
{/* 这里可以根据productId获取并展示具体产品信息 */}
</div>
);
});
其他页面组件(ProductCategoriesPage.tsx
、ProductsByCategoryPage.tsx
、ProductsBySubCategoryPage.tsx
)的实现思路类似,通过useRouteParams
获取参数,并根据参数进行数据获取和展示。这种设计既满足了不同类别产品展示及详情查看的需求,又对SEO友好,同时提供了较好的用户体验。