面试题答案
一键面试Next.js
- 路由规则定义:Next.js 使用文件系统来定义路由。在
pages
目录下,通过在文件名中使用方括号[]
来定义动态路由。例如,创建pages/products/[productId].js
文件表示匹配/products/:productId
这样的动态路由。 - 参数获取:在页面组件中,可以通过
getStaticProps
或getServerSideProps
的上下文对象context
中的query
属性获取动态参数。import React from'react'; export async function getStaticProps(context) { const productId = context.query.productId; // 可以根据 productId 从数据库等获取数据 return { props: {}, revalidate: 60 // 可选,用于增量静态再生 }; } const ProductPage = () => { return ( <div> Product Page </div> ); }; export default ProductPage;
Vue Router
- 路由规则定义:在Vue Router中,通过在路由配置数组中定义动态路由。例如:
import Vue from 'vue'; import Router from 'vue-router'; import ProductPage from '@/components/ProductPage.vue'; Vue.use(Router); export default new Router({ routes: [ { path: '/products/:productId', name: 'product', component: ProductPage } ] });
- 参数获取:在组件内部,可以通过
$route.params
获取动态参数。<template> <div> <h1>Product Page</h1> <p>Product ID: {{ $route.params.productId }}</p> </div> </template> <script> export default { name: 'ProductPage' }; </script>
两者不同点总结
- 定义方式:Next.js 基于文件系统,Vue Router 基于配置数组。
- 参数获取时机与方式:Next.js 在数据获取函数(
getStaticProps
等)中通过上下文获取,Vue Router 在组件内部通过$route
对象获取。