能否实现动态路由?根据请求路径匹配组件并分配默认组件
Absolutely! This kind of dynamic route resolution is totally feasible with Vue Router, though your initial code has a small issue: you can't access the slug route parameter directly when defining the routes array (since that value only exists when a request is made, not at router initialization).
Here's how to fix it and make it work correctly:
First, we'll need a helper function to convert the kebab-case slug from the URL (like foo-bar) to PascalCase (like FooBar) to match your component imports:
// Helper to convert kebab-case to PascalCase const kebabToPascal = (str) => { return str.split('-').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(''); };
Then, update your router configuration to use a component factory function instead of directly resolving the component. This function receives the route object, so we can extract the slug and resolve the component dynamically when the route is accessed:
import * as pages from '../components/pages'; import BasePage from '../components/BasePage.vue'; import Home from '../components/Home.vue'; const router = new Router({ routes: [ { path: '/', name: 'Home', component: Home }, { path: '/:slug', component: (to) => { const pascalSlug = kebabToPascal(to.params.slug); // Check if the component exists in our imported pages const targetComponent = pages[pascalSlug] || BasePage; return Promise.resolve(targetComponent); }, props: true } ] });
Key Details:
- The component factory function runs every time the route is navigated to, so it can access the current route's
params(includingslug). - We convert the kebab-case slug from the URL to PascalCase because your imported components are stored under PascalCase keys (e.g.,
pages.FooBarfor theFooBarcomponent). - If the component doesn't exist in the
pagesobject, we fall back toBasePageas requested. - Returning a resolved Promise is required here (Vue Router expects async components to return a Promise, even if the resolution is synchronous).
This setup will correctly route /foo-bar to the FooBar component if it exists, or BasePage if it doesn't.
内容的提问来源于stack exchange,提问作者sazr

