DEV Community

Cover image for Most Important Topics of VueJs Router
Ajay Yadav
Ajay Yadav

Posted on • Updated on

Most Important Topics of VueJs Router

In this tutorial we will learn every important topic of vuejs router , we will cover most of the important topics which will help you to understand batter. I assume you already familiar with vuejs router.

Dynamic routing

if you want to pass slug or id in particular vue page then dynamic routing can help you.

Alt Text

Here ArticleDetail is a vue page or template where we write everying about the article detail. so we can access slug in that page with the help of '$route.params.slug'; and also we can make little bit deep routing also /user/:username/article/:articlce_id

Reacting to Params Changes

If you show details of article pages and on the same page you want to list other articles in carousel and after the clicking that carousel you want to change the content of the article according to slug.

Alt Text

Catch all (404 Not found Route)

Alt Text
Write it at the end of the all routes

Nested Routes

Composed of components that are nested multiple levels deep.

Alt Text

Note that nested paths that start with / will be treated as a root path
In the user template we need to write

<router-view />

so the children routes templates will be displayed in the user template.

Programmatic Navigation

Alt Text

Named Routes

You can give a route a name in the routes options while creating the Router instance:

{path: '/user/:userId',name: 'user',component: User}

<router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>
Enter fullscreen mode Exit fullscreen mode

Redirect routes

Redirecting is also done in the routes configuration. To redirect from /a to /b

{ path: '/a', redirect: '/b' }

Global Before Guards

Global before guards are called in creation order, whenever a navigation is triggered. Guards may be resolved asynchronously, and the navigation is considered pending before all hooks have been resolved. This will help you to privatised some routes.

Alt Text

now in the routes.js file we can add meta fields, which route needs to be authenticated.Helpful for authentication

{ path: '/foo',component: Foo,meta: { requiresAuth: true }
Enter fullscreen mode Exit fullscreen mode

Scroll Behavior

So when you navigate to another page you want to control scroll behaviour , like when user enters on the page you want to scroll on the top of the page you can define it in routes.

Alt Text

You can add active class also with the help of vue router.

Lazy loading

When building apps with a bundler, the JavaScript bundle can become quite large, and thus affect the page load time. It would be more efficient if we can split each route's components into a separate chunk, and only load them when the route is visited.
Alt Text

Top comments (1)

Collapse
 
bgrand_ch profile image
Benjamin Grand

Thanks a lot, very well explained and illustrated!