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

Head back to your browser and enter #/user/sarah at the end of your URL. You should


see Hello sarah in the main body of your web page. Viewing the JavaScript browser


console, you should see the params object has a key/value pair of name: sarah within it:


This variable is also available to us within the component itself. For example, if we wanted


to capitalize the first letter of our user's name, we could make a computed variable which
takes the route parameter and transforms it:


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

If you're not familiar with what the preceding code is doing, it takes the first character of


the string and makes it uppercase. It then splits the string after the first character (that is,
the rest of the word) and appends it on the uppercase letter.


Adding this computed function and refreshing the app will yield Hello sarah.


As mentioned, the route can accept as many parameters as you want and can be separated


by static or dynamic variables.


Changing the path to the following (while keeping the component name the same):


/:name/user/:emotion
Free download pdf