Rendering data on the page
We've just created a Vue app instance and mounted it to the page, so let's now get it to actually modify our page somehow.
One of the most basic things that Vue can do is render JavaScript data, so let's get it to do that.
See on our page here that we've got a value for the total of all the cart contents. Currently, that value is hardcoded in the page. Let's instead replace this with dynamic JavaScript data.
Vue app config
Many of the features and functionality of your Vue app will be defined by the configuration object you pass to the app instance when you create it.
So let's pass an empty object to our createApp
method which we'll be adding to as we progress through the course.
public/script.js
Vue.createApp({}).mount("#app");
Data properties
One of the most common functions of a Vue app is that it can manage the "state" of your app. Said another way, it can keep track of values including numbers, or booleans, or strings, as well as objects, and arrays.
To do this, we'll need to add our first property to the app config object which will be data
. This is a function which returns an object containing our app state.
So let's make data
a function property, and in the function, we'll return an object.
public/script.js
Vue.createApp({
data() {
return {};
}
}).mount("#app");
As I said a moment ago, we want our app to display the total of the cart contents. So let's add a property to this object total
. We'll give this property an inital value of 0
.
public/script.js
Vue.createApp({
data() {
return {
total: 0
};
}
}).mount("#app");
Interpolation
Now our Vue app is managing state for us, specifically the value total
. How can we now render this value in the page?
Firstly, let's get rid of the hardcoded value, and replace it with a pair of curly braces. Inside those braces we'll reference our state property total
.
index.html
<div class="products">
<p>Total: {{ total }}</p>
</div>
If we save that, you can see on the page it now says "Total: 0", which is what we'd hoped for.
This is what we call an "interpolation". It basically means that some JavaScript value is rendered in the page.
To be sure this is working how we think, let's change the value of total
to something else, like 1
, let's say, and save again, you can see that that's what we see in the page instead.
Let's change that back to 0
, though, before we go to the next video where we'll be learning about an important feature of Vue called "directives".
Click to load comments...