Understanding Routing in Vue.js
Routing is an essential feature in web application development. In Vue.js, we can use Vue Router to easily manage navigation between pages. In this post, we’ll explore how to set up routing in a Vue.js application.
What is Vue Router?
Vue Router is the official library for managing routing in Vue.js applications. With Vue Router, we can create single-page applications (SPAs) that allow smooth navigation without reloading the page.
Installing Vue Router
First, we need to install Vue Router. If you are using Vue CLI, you can select to install it while creating a new project. If not, you can install it with the following command:
npm install vue-router
Setting Up Vue Router
After installation, we need to configure Vue Router. Here are the basic steps to set it up:
-
Create a Router File
Create a new file named
router.js
inside thesrc
folder: import Vue from 'vue'; import Router from 'vue-router'; import Home from './views/Home.vue'; import About from './views/About.vue';
Vue.use(Router);
export default new Router({
mode: 'history', // Using history mode for cleaner URLs
routes: [
{
path: '/',
name: 'home',
component: Home,
},
{
path: '/about',
name: 'about',
component: About,
},
],
});
-
Integrate Router into the Application
Next, we need to integrate the router into our Vue instance. Edit the
main.js
file as follows:
import Vue from 'vue';
import App from './App.vue';
import router from './router';
new Vue({
el: '#app',
router, // Add the router to the Vue instance
render: h => h(App),
});
-
Using Router Links
To navigate between pages, we use the
<router-link>
component. Here’s an example of how to use it in theApp.vue
file:
<template>
<div id="app">
<nav>
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
</nav>
<router-view></router-view> <!-- Place to display the matched component -->
</div>
</template>
-
Creating New Pages
Now, let’s create two components that we will use:
Home.vue
andAbout.vue
.
Home.vue
:
<template>
<div>
<h1>Welcome to the Home Page!</h1>
</div>
</template>
<script>
export default {
name: 'Home',
};
</script>
About.vue
:
<template>
<div>
<h1>This is the About Page</h1>
</div>
</template>
<script>
export default {
name: 'About',
};
</script>
Now you can run your application with the command:
npm run serve
Open your browser and go to http://localhost:8080. Try clicking on the Home and About links to see how routing works!
Conclusion
In this post, we’ve covered the basics of routing in Vue.js using Vue Router. With this routing capability, you can build more interactive and user-friendly applications. In the next post, we can delve into more advanced features of Vue Router, such as route parameters and nested routes.
I hope you found this post helpful! Feel free to leave a comment if you have any questions.
Top comments (0)