It is incredibly common to re-use complex elements throughout a front-end web app. For example, every post on Instagram or Facebook needs to look the same but contain different information. Additionally, they need to look the same on many different pages within the site and on many different devices. To make this easier, Vue has added the ability to create custom, reusable HTML elements called components.
When creating a component, you provide a template that should be rendered whenever the component is used in HTML. You then specify which pieces of dynamic information, called props, the component can receive to fill in this template. When used in your HTML code, props look like normal HTML attributes, you add them to the opening tag of the component HTML element with a name and a value.
Once you’ve created your component, you can then use it throughout your site just like any other HTML element. This means no copy/pasting of HTML code, no need to make the same change in multiple places across your site, and no potentially broken or misstyled elements.
Knowing how and when to make components is a slightly more advanced topic, so we won’t cover it in depth. However, that doesn’t mean we can’t play around with them right now. Let’s check one out!
In the future, we will likely need to display our tweets in many different sections of our site. To make this task easier and less prone to errors, we’ve created a
tweet component to be used throughout the site.
In Tweet.js, you’ll see the code to create a new component called
tweet that takes in a prop called
message and displays it using the supplied
template. Much like with a Vue app, all of this information is passed in as an options object.
You’ll notice that the username in the
template is still hard-coded as
CoderInTraining. Let’s change this so that the author can also be provided as a prop.
'author' to the
props array so that our component can accept the username of the tweet’s author as a prop.
Next, let’s update the component’s template to use the passed-in value of
CoderInTraining in the component’s template with a mustache expression that will evaluate to
Finally, let’s pass in the value of
username to the
author prop on our component using the
v-bind takes a value from the Vue app’s
data object and uses it as the value of the specified component prop.
You can see an example of this on line 27 of index.html. We use
v-bind to set the value of
message on the tweet component instance,
<tweet>, to be the Vue app
data‘s value of
The name of the value after the
: is the prop that will be receiving the value. The value of
v-bind (the name in quotes) is the
data value we will be using to set that prop’s value.
In index.html, add a
v-bind directive to our
<tweet> element that passes in the value of
author. This should look very similar to the other
v-bind expression on the element.