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

The component would then be used in the view like so:


<heading text="Hello!"></heading>

With props, we don't need to define the text variable in the data object, as defining it in


the props array automatically makes it available for use in the template. The props array
can also take further options, allowing you to define the type of input expected, whether it


is required or a default value to use if omitted.


Add a prop to the balance component so we can pass the cost as an HTML attribute. Your
view should now look like this:


<balance cost="1234"></balance>

We can now add the cost prop to the component in the JavaScript, and remove the fixed
value from our data function:


template: '<div>{{ formattedCost }}</div>',
props: ['cost'],
data() {
return {
currency: '$'
}
},

Running this in our browser, however, will throw an error in our JavaScript console. This is


because, natively, props being passed in are interpreted as strings. We can address this in


two ways; we can either convert our prop to a number in our formatCost() function or,


alternatively, we can use the v-bind: HTML attribute to tell Vue to accept the input for


what it is.


If you remember, we used this technique with our filters for the true and false


values—allowing them to be used as Boolean instead of strings. Add v-bind: in front of


your cost HTML attribute:


<balance v-bind:cost="15234"></balance>

There is an extra step we can do to ensure Vue knows what kind of input to expect and
informs other users of your code as to what they should be passing to the component. This


can be done in the component itself and, along with the format, allows you to specify
default values along with whether the prop is required or not.

Free download pdf