Complete Vue.js 2 Web Development_ Practical guide to building end-to-end web development solutions with Vue.js 2

(singke) #1
Introducing Vue-Router and Loading URL-Based Components Chapter 8

Navigating to /user should reveal the same sentence as we had before. Passing props


"behind the scenes" (not using the URL) is ideal in some scenarios where you may not want


the user to share the specific URL or alter the app's state based on easily altered parameters.


Nested routes


Nested routes differ from sub-routes as they exist within a component already matching the
beginning part of a route. This allows you to show different content within an existing


view.


A good example of this would be Twitter. If you visit a Twitter user's profile page, you are


able to view who they are following, who follows them, and what lists they've created. If


you observe the URL while you navigate through the pages, you will notice a recurring
pattern: the username followed by the different page. The difference between nested routes


and sub-routes is that nested routes allow you to keep components the same throughout
the different sub-pages (for example, the header and sidebar).


The advantages of this are that the user can bookmark and share the link, it makes the page


more accessible, and is good for SEO reasons. None of these advantages could be easily
achieved using simple toggle or tab boxes to show different content in the view.


To reproduce the Twitter pattern into a Vue route, it would look like the following:


https://twitter.com/:user/:page

If we were to create this with the previous route method, we would have to build


components for each page which contain the header and user information in the sidebar in
their templates—that would be a pain if you needed to update the code!


Let's make some nested routes for our About page. We won't be using nested routes in our
shop app, but it's important to understand the capabilities of Vue router.


Create two new components—AboutContact, which will display contact information, and


AboutFood, a component that will detail the food you like to eat! Although not required,


it's a good idea to keep a reference to the parent component (in this case, About) in the
component name—this ties together the components when you come to look at them later


on! Give each component a template with some fixed content:


const AboutContact = {
template: `<div>
<h2>This is some contact information about me</h2>
<p>Find me online, in person or on the phone</p>
</div>`
Free download pdf