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

Convert your props array to an object, with cost as the key. If you are just defining the


field type, you can use the Vue shorthand for declaring this by setting the value as the field


type. These can be String, Number, Boolean, Function, Object, Array, or Symbol. As our


cost attribute should be a number, add that as the key:


props: {
cost: Number
},

It would be nice if, rather than throwing an error when nothing is defined, our component
rendered $0.00. We can do this by setting the default to just 0. To define a default we need


to convert our prop into an object itself - containing a type key that has the value of


Number. We can then define another default key and set the value to 0 :


props: {
cost: {
type: Number,
default: 0
}
},

Rendering the component in the browser should show whatever value is passed into the
cost attribute—but removing this will render $0.00.


To recap, our component looks like :


Vue.component('balance', {
template: '<div>{{ formattedCost }}</div>',

props: {
cost: {
type: Number,
default: 0
}
},

data() {
return {
currency: '$'
}
},

computed: {
formattedCost() {
return this.currency +
this.cost.toFixed(2);
}
Free download pdf