Introduction
Vue Router is the official router for Vue.js. It deeply integrates with Vue,js core to make building Single Page Applications with Vue.js a breeze. Features include:
- Nested routes mapping
- Dynamic Routing
- Modular, component-based router configuration
- Route params, query, wildcards
- View transition effects powered by Vue.js' transition system
- Fine-grained navigation control
- Links with automatic active CSS classes
- HTML5 history mode or hash mode
- Customizable Scroll Behavior
- Proper encoding for URLs
Installation
Essential
Getting Started
Creating a Single-page Application with Vue + Vue Router feels natural: with Vue.js, we are already composing our application with components. When adding Vue Router to the mix, all we need to do is map our components to the routes and let Vue Router know where to render them. Here's a basic example:
HTML
<script src="https://unpkg.com/vue@3"></script>
<script src="https://unpkg.com/vue-router@4"></script>
<div id="app">
<h1>Hello App!</h1>
<p>
<!-- use the router-link component for navigation. -->
<!-- specify the link by passing the `to` prop. -->
<!-- `<router-link>` will render an `<a>` tag with the correct `href` attribute -->
<router-link to="/">Go to Home</router-link>
<router-link to="/about">Go to About</router-link>
</p>
<!-- route outlet -->
<!-- component matched by the route will render here -->
<router-view></router-view>
</div>
Javascript
// 1. Define route components.
// These can be imported from other files
const Home = { template: '<div>Home</div>' }
const About = { template: '<div>About</div>' }
// 2. Define some routes
// Each route should map to a component.
// We'll talk about nested routes later.
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About },
]
// 3. Create the router instance and pass the `routes` option
// You can pass in additional options here, but let's
// keep it simple for now.
const router = VueRouter.createRouter({
// 4. Provide the history implementation to use. We are using the hash history for simplicity here.
history: VueRouter.createWebHashHistory(),
routes, // short for `routes: routes`
})
// 5. Create and mount the root instance.
const app = Vue.createApp({})
// Make sure to _use_ the router instance to make the
// whole app router-aware.
app.use(router)
app.mount('#app')
// Now the app has started!
By calling app.use(router), we get access to it as this.$router as well as the current route as this.$route inside of any component.
Home.vue
// Home.vue
export default {
computed: {
username() {
// We will see what `params` is shortly
return this.$route.params.username
},
},
methods: {
goToDashboard() {
if (isAuthenticated) {
this.$router.push('/dashboard')
} else {
this.$router.push('/login')
}
},
},
}
Throughout the docs, we will often use the router instance. Keep in mind that this.$router is exactly the same as directly using the router instance created through createRouter. The reason we use this.$router is because we don't want to import the router in every single component that needs to manipulate routing.
Dynamic Route Matching with Params
Route params passing
- $route.params
Now URLs like /users/johnny and /users/jolyne will both map to the same route.
When a route is matched, the value of its params will be exposed as this.$route.params in every component.
- $route.query
this $route object also exposes other useful information such as $route.query (if there is a query in the URL), $route.hash, etc.
Reacting to Params Changes
One thing to rote when using routes with params is that when the user navigates from /users/johnny to /users/jolyne, the same component instance will be reused. However, this also means that the lifecycle hooks of the component will not be called.
To react to params changes in the same component, you can simply watch anything on the $route object, in this scenario, the $route.params:
Or, use the beforeRouteUpdate navigation guard, which also allows to cancel the navigation:
Nested Routes
Some application's UIs are composed of components that are nested multiple levels deep. In this case, it is very common that the segments of a URL corresponds to a certain structure of nested components, for example:
APP.vue
account.vue
router.js
router/account/index.js
Passing Params to Route Components
Programmatic
Method
router.push(...)
Theory
- This method pushes a new entry into the history stack, so when the users clicks the browser back button they will be token to the previous URL.
Argument
- The argument can be a string path, or a location descriptor object. Examples:
// literal string path
router.push('home')
// object
router.push({ path: 'home'})
// named route
router.push({ name: 'user', params: { userId: '123'} }) // -> /user/123
router.push({ name: 'user', query: { userId: '123'} }) // -> /user?userId=123
// path route
router.push({ path: '/user', query: { userId: '123'} }) // -> /user?userId=123
const userId = '123'
router.push({ path: `/user/${userId}` }) // -> /user/123
// This will NOT work
router.push({ path: '/user', params: { userId: '123'} }) // -> /user
Note: params are ignored if a path is provided, which is not the case for query.
Declarative
<router-link :to="...">
Theory
- This is the method called internally when you click a
<router-link :to="...">is the equivalent of callingrouter.push(...). - The some argument rules apply for the to property of the
<router-link>component.
Props
- Using
$routerin your component creates a tight coupling with the route which limits the flexibility of the component as it can only be used on certain URLs. - To decouple this component from the router use option
props.
example, VueRouter passing params1, VueRouter passing params2