0
0
Vueframework~30 mins

Pages and file-based routing in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Building Pages with File-Based Routing in Vue
📖 Scenario: You are creating a simple website with multiple pages using Vue's file-based routing system. Each page will be a separate Vue component file inside the src/pages folder. The router will automatically create routes based on these files.
🎯 Goal: Build a Vue project with two pages: Home and About. Use file-based routing so that navigating to / shows the Home page and navigating to /about shows the About page.
📋 What You'll Learn
Create Vue component files inside src/pages folder
Use file-based routing to automatically generate routes
Create a Home page component with a heading 'Home Page'
Create an About page component with a heading 'About Page'
Set up the Vue router to use the pages folder for routes
💡 Why This Matters
🌍 Real World
File-based routing is used in many modern Vue projects to simplify route management by automatically generating routes from files.
💼 Career
Understanding file-based routing helps you work efficiently on Vue projects and frameworks like Vite or Nuxt that use this pattern.
Progress0 / 4 steps
1
Create the Home page component
Create a Vue component file called src/pages/Home.vue. Inside it, write a template with a <h1> heading that says Home Page.
Vue
Hint

Use the <template> tag and inside it add <h1>Home Page</h1>.

2
Create the About page component
Create a Vue component file called src/pages/About.vue. Inside it, write a template with a <h1> heading that says About Page.
Vue
Hint

Similar to the Home page, use <template> and add <h1>About Page</h1>.

3
Set up the Vue router to use file-based routing
In your router setup file (e.g., src/router/index.js), import createRouter and createWebHistory from vue-router. Then create a router using createRouter with history set to createWebHistory() and routes set to an empty array. Finally, export the router as default.
Vue
Hint

Use createRouter with history: createWebHistory() and an empty routes array. Export the router as default.

4
Enable file-based routing with auto-import of pages
Modify the router setup to use file-based routing by importing import.meta.glob to automatically load all Vue files from src/pages. Use Object.entries on import.meta.glob('../pages/*.vue') to create routes where the path is the filename converted to lowercase and prefixed with a slash (use '/' for Home.vue). Assign these routes to the routes array in the router. Export the router as default.
Vue
Hint

Use import.meta.glob to get all page components, then map them to route objects with paths based on filenames. Use '/' for Home.vue and lowercase names for others.