To create a Single-page app with vue.js, we have to add a router library to route URLs (Uniform Resource Locators) to our components.
Vue.js has its own router library called vue-router which handles routing.
In this article, we’ll take a look at how to use Vue Router in vue.js app.
Getting Started
We can get started using Vue Router in our Vue.js app in three ways:
Installing Vue Router directly or using
CDN
(content delivery network) in the Vue app.Adding Vue Router to the dependencies while setting up Vue.js app using Vue CLI.
Installing Vue-Router with NPM or yarn.
Importance of Vue Router
Vue Router works just like the anchor tag
( in HTML
(HyperText Markup Language). It is responsible for loading pages, that is you can use it to move from one page to another with the help of router-link and router-view component .
Creating a Single-page Application with Vue + Vue Router
You can install Vue Router directly with CDN(Content Delivery Network) in the following ways:
Get the URL to the npm-base CDN link( https://unpkg.com/vue@3 and https://unpkg.com/vue-router@4) from Vue Router site.
Then add the link to the script tag in our component.
Then map our components to the routes and let Vue Router know where to render them.
Then create the javaScript file(index.js), where we’ll add our code for the route components and do the routing.
To do all that is mentioned above, we will write the following code:
Index.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>
In the code above we have the script tags
which are used to link to Vue and Vue Router packages, then we have the div tag
with an id
attribute that is set to app.
router-view
The router-view is a component that comes with Vue Router, router-view is used to display our content inside the div
tag or component that corresponds to the url.
router-link
The router-link
is also a component that comes with Vue Router, router-link
works like the anchor tag
. router-link
comes with a to
property(prop)
to pass the path or URL address where we want the links to go to. router-link
is used to create links.This allows Vue Router to change the URL without reloading the page. You can put it anywhere in the layout.
Index.js(javascript file)
Finally, we have the index.js file.
/ 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!
In the code above, we have Home and About routes to show home
and about
pages respectively.
Then, we use the routes array to map the components to the paths which we want to map the routes to.
Next, we created a new instance of VueRouter with an object that has our routes and history in it.
Adding Vue Router to the dependencies while setting up Vue.js app using Vue CLI
You can add Vue Router to your Vue app while installing Vue with Vue CLI with the following:
- Run “vue create project-name” in your terminal. You will be prompted to pick a preset.
- Select
manually select features
to pick Router. You will be prompted to pick the version of Vue you want to use, then pick any and after that, you will be prompted again to answer yes or no to this question:Use history mode for router?
(Requires proper server setup for index fallback in production)(y/n)
. - Type
y
if you wanthistory mode
, else typen
if you don’t want it. You will be prompted for other features. - Use the enter key to select the next prompted features that come up.
- Type
y or n
to this prompted question (Save this as a preset for future projects?).if you typey
, at the end of the prompts you’ll have the option to save your selections as a preset so that you can reuse it in the future, if you typen
you won’t be able to reuse the preset in future.
After all the above steps to install Vue and Vue Router with Vue CLI is completed, the Vue Router will be set up automatically, whereby a folder named router will be created inside the vue project and inside the folder there will be a file (index.js
) for the router, then you can start using the router-link
and router-view
.
Installing Vue-Router with NPM or yarn
You can install Vue Router with NPM
or yarn
by running this code:
Run
npm install vue-router@4
in your terminal, if you want to install Vue Router withNPM
.Run
yarn add vue-router@4
in your terminal, if you want to install Vue Router withyarn
.
What dynamic matching route does
Dynamic matching route is when multiple routes share the same component. For example, when we many movies with different id and we want to show the users profile, the user’s profile component is the component that will be used for all the users to view their profile.
Dynamic matching route can be done by mapping a route with a given pattern to the same components with params
and the url
will be like this /users/1
. For example, we may have a component movie which should be rendered for all users but with different IDs
. this is the template on how to make a dynamic route:
app.mount('#app');
const User = {
template: '<div>User</div>',
}
// these are passed to `createRouter`
const routes = [
// dynamic segments start with a colon
{ path: '/users/:id', component: User },
]
To add a param to the route path, a param is denoted by a colon :
. when the route is matched, the value of its params will be exposed as this.$route.params
in every component.
Therefore, we can render each movie by updating the movie template to this:
const User = {
template: '<div>User {{ $route.params.id }}</div>',
}
Route with params enables users to navigate from /user/1
to /user/2
whereby the same component instance will be reused, because both routes are using the same component.
Top comments (0)