Home > Article > Web Front-end > Vue.js for Beginners A Complete Guide to Routing with Vue Router
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.
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.
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
After installation, we need to configure Vue Router. Here are the basic steps to set it up:
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, }, ], });
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), });
<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>
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!
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.
The above is the detailed content of Vue.js for Beginners A Complete Guide to Routing with Vue Router. For more information, please follow other related articles on the PHP Chinese website!