MST

星途 面试题库

面试题:Next.js路由系统与Vue Router在动态路由匹配上的区别

请阐述Next.js路由系统和Vue Router在处理动态路由匹配时的方式有何不同,例如在参数获取、路由规则定义等方面。并分别举例说明如何在Next.js和Vue Router中实现动态路由匹配,包括路径定义和参数的提取与使用。
33.9万 热度难度
前端开发Next.js

知识考点

AI 面试

面试题答案

一键面试

Next.js

  1. 路由规则定义:Next.js 使用文件系统来定义路由。在 pages 目录下,通过在文件名中使用方括号 [] 来定义动态路由。例如,创建 pages/products/[productId].js 文件表示匹配 /products/:productId 这样的动态路由。
  2. 参数获取:在页面组件中,可以通过 getStaticPropsgetServerSideProps 的上下文对象 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

  1. 路由规则定义:在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
            }
        ]
    });
    
  2. 参数获取:在组件内部,可以通过 $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 对象获取。