Vue Router
For most single-page applications (SPAs), we need a way to navigate users to different parts of the application without refreshing the entire page. Vue Router is Vue.js's official routing manager, deeply integrated with Vue's core, making it easy to build SPAs with routing functionality.
Installation
If you chose to add Vue Router when creating your project with create-vue, then everything is already configured for you. If not, you can manually install it:
Then, you need to create a router instance and mount it onto the Vue application.
src/router/index.js
src/main.js
Core Concepts
1. router-link
router-link is a component used for declarative navigation. It renders as an <a> tag with the correct href. When a user clicks it, it calls router.push() internally, thus changing the URL without reloading the page.
2. router-view
router-view is a functional component that renders the view component that matches the path. You can place it anywhere to adapt to your layout.
3. Dynamic Route Matching
We often need to map all routes matched by a certain pattern to the same component. For example, we might have a User component that should be used to render all users with different IDs. We can achieve this by using dynamic segments in the path:
Now, URLs like /users/johnny and /users/jolyne will both map to the same route.
Inside the component, you can access these dynamic segments through $route.params.
User.vue
4. Route Lazy Loading
When building an application, the JavaScript bundle becomes very large, affecting page loading. If we can split code for different routes into separate chunks, then load the corresponding component only when the route is accessed, it's more efficient. Vue Router supports this "lazy loading" mechanism.
This way, the AboutView.vue component will be packaged as an independent chunk and will only be loaded when the user accesses the /about path.