In this lesson we’ll be uncovering how to conditionally display elements with Vue.
We want to display text that says if our product is in stock or not, based on our data.
Notice we’ve added a new data property there at the bottom:
Often in a web application, we want elements to appear on the page depending on if a condition is met or not. For instance, if our product is not in stock, our page should display the fact that it’s out of stock.
So how could we conditionally render these elements, depending on whether our product is in stock or not?
Vue’s solution is simple and straightforward.
Given that our data contains this new property:
We can use the
v-else directives to determine which element to render.
inStock is truthy, the first paragraph will render. Otherwise, the second paragraph will. In this case, since the value of
inStock is true, the first paragraph will render.
Great. We’ve used conditional rendering to display whether our product is in stock or not. Our feature is done. But let’s explore conditional rendering some more before we move onto our next topic.
We can add a third degree of logic with
v-else-if. To demonstrate, let’s use an example that is a bit more complex.
If our data looked something like this:
We could use expressions, inside the quotes, to make our conditions more specific.
The element that will render is the first element whose expression evaluates to true.
If your app needs an element to frequently toggle on and off the page, you’ll want to use the
v-show directive. An element with this directive on it will always be present in our DOM, but it will only be visible on the page if its condition is met. It will conditionally add or remove the CSS property
display: none to the element.
This method is more performant than inserting and removing an element over and over with
However, in the product app we’re building, using a
v-else works just fine, so we’ll keep that as our solution.
onSale property to the product’s data that is used to conditionally render a
span that says “On Sale!”