As you work with Vue.js, you might wonder how to navigate between pages in your Vue app. That's where Vue Router comes in. Vue Router is the official routing library for Vue.js, designed for creating single-page applications (SPAs). Think of it as a road map for your app, guiding users from one view to the next. In this topic, you will learn the basics of Vue Router, how to set it up, what defined routes are, and how Vue Router helps you to navigate through your app.
Vue router
Vue Router is a tool that lets you define routes (or paths) in your Vue.js applications. Each route corresponds to a specific component. When a user accesses that route, Vue Router handles the rendering of the associated component. It's like having a personal tour guide in your app, ensuring users get where they need to go.
One of the main features of Vue Router is its integration with Vue.js core. This integration makes it easy to connect with your Vue components, making them as reactive as the rest of your application. Vue Router is critical for creating complex applications with nested views, modular and component-based configurations, and handling various route parameters. For example, it allows you to load different components based on the user's role or load different views based on the URL parameters.
Setting up vue router
Setting up Vue Router in your Vue 3 application is simple. First, you need to install it. If you're using npm, you can do this by running npm install vue-router@next.
Once you've installed Vue Router, you can import it into your main.js file and create a new router instance. In simple terms, creating a new router instance means setting up the configuration for the routes in your application.
Here's a basic example:
// App.vue
<template>
<div id="app">
<router-view></router-view>
</div>
</template>
<script>
import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import Home from './components/Home.vue'
import About from './components/About.vue'
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
})
createApp(App).use(router).mount('#app')
</script>In this example, we import the createRouter and createWebHistory functions from vue-router, which are used to create the router instance and define the history mode for navigation.
Then, we create a new router instance using the createRouter function. We pass an object as an argument with two properties:
history. The
historyproperty is set tocreateWebHistory(), which creates a history object based on the browser's history API.routes. The
routesproperty is an array of route objects. In this example, we have two routes:'/'and'/about', each linked to theHomeandAboutcomponents, respectively.
Finally, we create a new Vue application instance using the use method to install the router instance into the application.
When the user navigates to '/', the Home component is rendered, and when they navigate to '/about', the About component is rendered.
Defining routes
Defining routes in Vue Router is all about mapping a path to a component. When that path is accessed, the associated component is rendered. You define your routes in the routes option when creating your router instance, just like we did in the example above.
Each route is an object with two properties: path and component. The path is the URL where the route should be active, and the component is the Vue component that gets rendered at that path.
For example:
routes: [
{ path: '/user', component: User }
]In this case, when the user navigates to /user, the User component renders.
To display the components associated with the defined routes, we need a placeholder in our application template. That's where the router-view component comes in. The router-view component acts as a placeholder that gets replaced with the component corresponding to the active route.
Here's an example that shows how to use router-view in your template:
<template>
<ul class="nav">
<li>
<router-link to="/">Home</router-link>
</li>
<li>
<router-link to="/about">About</router-link>
</li>
</ul>
<router-view></router-view>
</template>
<script>
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
})
createApp(App).use(router).mount('#app')
</script>And the output will be:
Navigation
For navigation in Vue Router, you have two main methods: router-link and programmatic navigation. Let's look at each method:
Using
router-linkrouter-linkis a component that provides a declarative way to navigate between different routes in your Vue.js application. Declarative here means that you just tell Vue what you want (i.e., navigate to a certain route), and Vue will take care of how to do it.router-linkgenerates an anchor tag (<a>) with the appropriate href attribute based on the specified route.Using
router-linkhas several advantages over manually creating anchor tags withhrefattributes. It automatically applies the active class when the corresponding route is active, making it easy to style the active link. It also handles the navigation behavior, preventing the page from refreshing when the link is clicked.The
<router-link>component is used like this:<router-link to="/about">Go to About</router-link>This will render an
<a>tag that, when clicked, will navigate to the/aboutroute.Programmatic navigation
Programmatic navigation in Vue Router refers to the ability to navigate between routes using JavaScript code instead of clicking on links or buttons. It provides control over the navigation flow and allows you to trigger route changes based on specific conditions or events in your application.
In Vue Router, programmatic navigation is achieved using the
router.pushmethod. For example:// Navigating to the '/about' route router.push('/about')router.push('/about')will navigate to the '/about' route. You can also pass additional options like query parameters or route parameters to customize the navigation:// Navigating to a dynamic route with a parameter router.push('/user/' + userId)To use
router.push, you need access to the router instance, which can be achieved by usingapp.use(router)when creating the Vue application. Here's a complete example:<template> <button @click="navigateToAbout">Go to About</button> </template> <script> import { createApp, ref } from 'vue' import { createRouter, createWebHistory } from 'vue-router' import Home from './components/Home.vue' import About from './components/About.vue' const router = createRouter({ history: createWebHistory(), routes: [ { path: '/', component: Home }, { path: '/about', component: About } ] }) const app = createApp(App).use(router).mount('#app') const navigateToAbout = () => { app.router.push('/about') } </script>
Conclusion
So far, we've learned that Vue Router is a routing library for Vue.js allowing us to define routes and navigate between different views in our applications. It integrates seamlessly with Vue.js and provides features such as nested route mapping, modular configuration, route parameters, and request handling.
Setting up Vue Router involves installing it, creating a router instance, and defining routes that map component paths. We can use the router-link component for declarative navigation and the router.push method for programmatic navigation.
Vue Router provides a seamless and efficient way to manage navigation in Vue.js applications, making it an essential tool for creating single-page applications.