Hello everyone!
Today I'll be helping you out getting into Vue.JS routing. It's really easy and I think that you will get into it very easy. This is my first post, I hope you will like it.
What is routing? ✈
Routing or router in web development is a mechanism where HTTP requests are routed to the code that handles them. To put simply, in the Router you determine what should happen when a user visits a certain page.
What we can use routing for? 🤔
Routing is mostly used to make website routes when visiting (e.g localhost:8080/home). This gives us a lot of functionality to work with. We can restrict people from visiting a page on our site if he e.g isn't logged in to access. Another good usage is when user tries to access a nonexistent website page we can redirect him to a certain page section (e.g '/not-found').
How to integrate Vue router? 😯
It's really easy to integrate Vue router into your project when starting it up. We will be creating our project in the Vue CLI which is really neat for creating new projects as it does everything for you.
After typing this portion we will manually select next features:
After that you can also add history mode for the router and let the app install.
Your App.vue file should look like this:
So 'router-link' is similar to our 'a' tag which we normally use to send someone to our designated link. The difference between those two is that 'router-link' sends you to the route you want to go and with that it renders the components of that route. The #id will always stay the same which means that it won't have to re-render to every component in order for it to work. It will stay as it should.
The next thing is the 'router-view' and to put it simply it just renders the components of each route you are currently visiting.
There is two ways you can create routes, I will show them in the next section.
The first object is an example of classic route you can integrate very easily as you see you just need to import the view you want to render on the route and set the object as you see on the picture.
The second object shows you how to lazy load a route. It is basically the same except of the last component argument. The difference is that this component is going to be lazy loaded. What is lazy loading a route and is it better?
Lazy loading a route is basically loading or downloading the route component upon it's rendering so we don't need to download every component we use. This is done because we can't predict if the client is going to visit that page and for the performance sake it is better to lazy load routes or in bundles.
This is basically the end of my first post I hope you like it and enjoy it! 📃
Top comments (0)