Routing in Single-Page Application Frameworks
First, you need to set up a new Vue 3 project. If you haven't installed Vue CLI on your system, you can do it by running:
npm install -g @vue/cli
Once Vue CLI is installed, create a new Vue 3 project:
vue create my-vue-app
Follow the prompts to set up your project. Make sure to select Vue 3 when given the choice.
Navigate to your project directory and install Vue Router. Since we are working with Vue 3, make sure to install the version compatible with Vue 3.
cd my-vue-app npm install vue-router@4
Now, let's set up routing in the main.js
file.
Replace the content of your main.js
file with the following code:
import { createApp } from 'vue'; import { createRouter, createWebHistory } from 'vue-router'; import App from './App.vue'; import HomeComponent from './components/HomeComponent.vue'; import AboutComponent from './components/AboutComponent.vue'; const routes = [ { path: '/', component: HomeComponent }, { path: '/about', component: AboutComponent } ]; const router = createRouter({ history: createWebHistory(), routes }); const app = createApp(App); app.use(router); app.mount('#app');
In this setup, we're importing Vue, Vue Router, and two components. We define routes and then create a router instance with those routes. Finally, we create the Vue app instance, inject the router, and mount it.
Now, create two components HomeComponent.vue
and AboutComponent.vue
in the components directory.
Create a file named HomeComponent.vue
in the components folder and add the following code:
<template> <div> <h1>Home Page</h1> <p>Welcome to the Home Page!</p> </div> </template> <script> export default { name: 'HomeComponent' } </script> <style> /* Add your styles here */ </style>
Similarly, create an AboutComponent.vue
file with the following content:
<template> <div> <h1>About Page</h1> <p>This is the About Page.</p> </div> </template> <script> export default { name: 'AboutComponent' } </script> <style> /* Add your styles here */ </style>
Modify your App.vue
file to include navigation links and a router-view.
<template> <div id="app"> <h1>Vue 3 Routing Example</h1> <nav> <router-link to="/">Home</router-link> | <router-link to="/about">About</router-link> </nav> <router-view></router-view> </div> </template> <script> export default { name: 'App' } </script> <style> /* Add your styles here */ </style>
Finally, you can run your app to see the routing in action:
npm run serve
Navigate to http://localhost:8080/ in your browser. You should see the home page, and you can navigate between the home and about pages using the links.