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

Using props for your route component is a better way to pass options and parameters into


your route, as it has many benefits. Firstly, it decouples the component from a specific URL
structure—as you'll see, we can pass props straight to the component itself. It also helps


make your route component clearer; the incoming parameters are clearly laid out within
the component itself, and the code is cleaner throughout the component.


Props only work with the dynamic routes—GET parameters would still be accessed with


the preceding technique.


Using the preceding example, declare the props for both the name and emotion


parameters. When using props with a URL-based variable, you will want to use the String


data type:


const User = {
template: `<h1>{{ name }} is {{ $route.params.emotion }}</h1>`,
props: {
name: String,
emotion: String
},
computed: {
name() {
let name = this.$route.params.name;
return name.charAt(0).toUpperCase() + name.slice(1);
}
}
};

We now have this.name available to us twice—through the props and through the


computed value. However, as we have this.name and this.emotion via the props, we


can update our component to use these variables, rather than the $route parameters.


To avoid conflicts with the prop, update the computed function to be called
formattedName(). We can also remove the variable declaration from the function, as the


new variable is a lot more readable:


const User = {
template: `<h1>{{ formattedName }} is {{ this.emotion }}</h1>`,
props: {
name: String,
emotion: String
},
computed: {
formattedName() {
return this.name.charAt(0).toUpperCase() + this.name.slice(1);
}
}
Free download pdf