Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
March 17, 2021 05:51 pm GMT

Vue.js 101 - Conditional rendering

Everyday, I publish here on Dev.to what I learn from my Vue course the day before.

Click follow if you want to miss nothing.

Without further ado here is a summary of my notes for day 3.

Conditional rendering

Sometime we only want to show content base on certain conditions. For example base on user type (regular or admin) we will show/hide a button, menus or others part of our page.

In Vue to use conditional we only have to use the v-if directive:

<div v-if="isAdmin">  This content is for user admin only</div> 

If the property isAdmin is true the div will be render, if false the div will not be render

Of course to make that example work we need to add a isAdmin property to data() method.

data() {    return {        message: 'Hello World Vue',        number1: 500,        number2: 250,        isAdmin: true    }},

In this case I set the isAdmin to true but in real app that value may come from a database or API. But, the principe will remain the same.

We can combine what we learn in yesterday lesson with this one and show/hide a section base on the click of a button.

<div v-if="showTitle">    Welcome to my app</diV><button @click="showTitle = !showTitle">    Toggle show title</button>

We then have to add a showTitle with default value of true to our app.js

data() {    return {        showTitle: true    }},

Now each time we click the button the title show/hide repeatedly.

If the showTitle is false it can be hidden but it is also possible to display something else.

<div v-if="showTitle">    Welcome to my app</diV><div v-else>    Sorry, no title</div><button @click="showTitle = !showTitle">    Toggle show title</button>

The v-else directive logic use with the same logic as a regular if-else statement in javascript.

Note if the v-if directive evaluate to false, the div will not be render at all in the DOM. When the directive will switch to true the DOM will be re-render with the div.

Sometime it could be more efficient or for many other reasons, to always render the div in the DOM but only show or hide in the browser. How to do that? Use the v-show directive,

<div v-show="isAdmin">  This content will always be render but not always show</div> 

The v-show directive work the same as the v-if but the div will always be present in the DOM. At run-time it will
display in the browser or not depend on the value it evaluate.

Conclusion

That's it for today. Tomorrow the journey continue, see you later! If you want to be sure to miss nothing click follow me here or on twitter!

Follow me on Twitter:


Original Link: https://dev.to/ericchapman/vue-js-101-conditional-rendering-3hp9

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To