In Vue, we can implement routing using the Vue Router library, which provides a way to navigate between different pages or views in a Vue single-page application (SPA).
It provides a powerful and flexible way to manage application navigation, enabling us to define routes, create nested routes and handle dynamic routing.
Single-Page Applications (SPAs): Build SPAs with multiple views or pages that dynamically update content based on the URL, allowing smooth and seamless navigation from one page to another page without a full page reload.
Nested Routing: It Allows us to create nested routes to organize our application's UI into hierarchical structures, such as `entertainment/ott/movies/movieName`.
Dynamic Routing: It Allows us to generate routes dynamically based on data from an API or other external sources, allowing for dynamic content rendering.
npm install vue-router@next # or yarn add vue-router@next
import { createRouter, createWebHistory } from 'vue-router'; import Home from './home.vue'; import Contact from './contact.vue'; const routes = [ { path: '/', component: Home }, { path: '/contact', component: Contact } ]; const router = createRouter({ history: createWebHistory(), routes }); export default router;
<!-- src/Home.vue --> <template> <div> <h1>Home Page</h1> <p>Welcome to the home page!</p> </div> </template> <script> export default { // Component definition }; </script>
<!-- src/Contact.vue --> <template> <div> <h1> Contact Page</h1> <p>Welcome to the Contact page!</p> </div> </template> <script> export default { // Component definition }; </script>
// src/main.js import { createApp } from 'vue'; import App from './App.vue'; import router from './router'; const app = createApp(App); app.use(router); app.mount('#app');
<!-- src/App.vue --> <template> <div id="app"> <router-link to="/">Home</router-link> <router-link to="/contact">Contact</router-link> <router-view></router-view> </div> </template> <script> export default { // Component definition }; </script>
With these steps, we can set up basic routing in our Vue application using Vue Router 4.
We can continue to add more routes and components as needed for our application.
Make sure to refer to the official Vue Router documentation for any further updates or changes.