Named Views — Transcript

Transcript of the free Vue.js lesson Named Viewswatch the video lesson.

With View Router, it's possible to provide routes with multiple views. That way, you can compose layouts at the route level. For instance, let's say that we wanted to add a left sidebar on the protected pages. How might we go about doing that?

Well, to begin with, we'll need to create a view component. And I'll call it left sidebar. And even though technically we'll use this as a page, it'll never be a page used all by itself. Therefore, I've decided to put it in the components directory.

Next, let me just paste the contents of this component in here. As you can see, it's just some links to the protected pages along with a little bit of styling. view, I'll use what's called a named view. This name view is the exact same thing as a normal router view, except that it has the name property.

You can think of it much like a name slot. Finally, just for styling purposes, I'll give our default router view a class of main view. And then I'll add some styles to make the left sidebar show up on the left-hand side. All right.

If we check things out in the browser now, you'll see that none of our pages include the left sidebar. That's actually pretty great because that means that we can now pick and choose which pages to include it on. All right, let's add it to the protected page and the invoice page. We can do this over in the router file.

instead of passing a component property to the route, will instead provide a components property that is component plural. And the value will become an object with the default view being defined like so. Now we can also specify the named route. vue file.

Cool. Let's do the same now for the invoices route as well. Awesome. Now let's see how it looks.

You can see that on the pages where we didn't provide the left sidebar as one of the components, everything still looks the same. However, when we go and visit any of the protected pages, perfect. We get the sidebar here on the left and it works for both the dashboard and the invoices page. Very cool.

You might've noticed that our page transition looks a little funky now though. To fix that, let's just wrap our left sidebar view with the same transition as the main view. Whoops, looks like we left something out. Ah, we left off the B slot.

Nice, that looks better. When going to the dashboard page, we do still get a little jump on the size of the sidebar here because of Flexbox, but that's really not important as far as Vue Router is concerned, so we'll just leave it alone. In conclusion, we're able to determine the layout of the page based on the way we set up the route in the router file. This is not an approach I've ever taken before in a real application, but with Vue Router, it's definitely possible.