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

We need to pass in a name and emotion variable to the URL for the component to render.


We can pass in as we did before, directly to the URL or, alternatively, use the to object


notation with a named route:


<router-link :to="{name: 'user', params: { name: 'sarah', emotion: 'happy'
}}">
Sarah is Happy
</router-link>

Viewing this in the browser will show the anchor link has been generated correctly:


/sarah/user/happy

This gives us the flexibility to rearrange the URL, using the variables, without needing to


update the rest of the app. If you wanted to pass parameters at the end of the URL (for
example, ?name=sarah), the params key can be changed to query, as it follows the same


format:


<router-link :to="{name: 'user', query: { name: 'sarah', emotion: 'happy'
}}">
Sarah is Happy
</router-link>

With the path reconfigured not to accept parameters, it will generate the following link:


/user?name=sarah&emotion=happy

Be careful when interchanging params and query - as they can affect
whether you use path or name. When using path, the params object will
be ignored, whereas the query one will not. To use the params object, you
need to use a named route. Alternatively, pass the parameters into the
path with the $ variable.

Named views


Vue router also allows you to name the views, letting you pass in different components to


different sections of the app. An example of this might be a shop, where you have a sidebar
and main content area. Different pages may utilize these areas in different ways.


The About page may use the main content to show the About content while using the
sidebar to show contact details. The shop page, however, will use the main content to list


the products and the sidebar for displaying the filters.

Free download pdf