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

(singke) #1
Optimizing your App and Using Components to Display Data Chapter 3

As with our Vue instance in Chapter 1, Getting Started with Vue.js, add a function to the


computed object that appends a currency symbol to the integer and ensures there are two


decimal places. Don't forget to add the currency symbol to your data function.


Update the template to output the computed value instead of the raw cost:


Vue.component('balance', {
template: '<div>{{ formattedCost }}</div>',
data() {
return {
cost: 1234,
currency: '$'
}
},
computed: {
formattedCost() {
return this.currency + this.cost.toFixed(2);
}
}
});

This is a basic example of a component, however, it is quite restricted with the fixed cost


on the component itself.


Passing data to your component – props


Having the balance as a component is great, but not very good if the balance is fixed.


Components really come into their own when you add the ability to pass in arguments and


properties via HTML attributes. In the Vue world, these are called props. Props can be
either static or variable. In order for your component to expect these properties, you need to


create an array on the component by using the props property.


An example of this would be if we wanted to make a heading component:


Vue.component('heading', {
template: '<h1>{{ text }}</h1>',

props: ['text']
});
Free download pdf