• 15 hours
  • Medium

Free online content available in this course.

course.header.alt.is_video

course.header.alt.is_certifying

Got it!

Last updated on 4/13/21

Manage Common Scenarios With Directives

Log in or subscribe for free to enjoy all this course has to offer!

What Are Directives?

When it comes to front-end problems that developers run into, there are common ones that occur time and time again. And rather than have everyone come up with their own way of doing common things like toggling the display of an element, Vue provides directives as a standard way to get the job done: 

Directives provide a standard way to solve common problems. They are very powerful and written semantically, so there is a low barrier to comprehending the code. Directives look like HTML attributes with one primary difference: they are all prefixed with  v-.  Some common directives you will encounter in Vue apps include:

  • v-if  ,  v-else-if  ,  v-else

  • v-show

  • v-for

  • v-bind

  • v-on

  • v-model

In this lesson, we will go over these directives and how you can use them to create powerful Vue apps that anyone can understand.

Toggle Content Visibility

One of the most common scenarios in any front-end application is the need to show or hide content based on certain conditions. For example, depending on a user's permission level, you will need to dynamically determine what content should or should not be shown. In Vue, this is done with two primary directives:  v-if  and  v-show.

v-if, v-else-if, v-else

As the directive keywords suggest, this follows the standard JavaScript if/then conditional for rendering. Here is a simple example:

<div id="app">
<!-- If the user has default permissions, display this -->
<section v-if="userPermission === 'default'">...</section>
<!-- If the user has admin permissions, display this instead -->
<section v-else-if="userPermission === 'admin'">...</section>
<!-- If the user does not have either permissions, display this -->
<section v-else>...</section>
</div>

v-show

While this directive might seem very similar to the  v-if  directive, they are not interchangeable.  v-show  is typically used to control the visibility of an element that is frequently toggled.  A common example is:

<div id="app">
<button>Display Modal</button>
<div v-show="showModal" class="modal">...</div>
</div>
<script>
const app = new Vue({
el: '#app',
data: {
showModal: false
}
})
</script>

The key difference between the two is that  v-show  toggles visibility of the HTML element using CSS while the  v-if  directive removes the element from the DOM entirely.

Looping Through Content

Another common scenario is when you need to repeat an HTML element to render data. This is done using the  v-for  directive which follows the standard JavaScript  for ... in  loop syntax. A common example of this is when you need tor render a list. In the shopping cart example from Lesson 3, this could be written as:

<div id="app">
<h1>Vue Mart</h1>
<h2>Shopping Cart</h2>
<ul>
<li v-for="item in shoppingCart">
{{ item.label }}: ${{ item.cost }}
</li>
</ul>
</div>
<script>
const app = new Vue({
el: '#app',
data: {
shoppingCart: [
{ label: 'Apples', cost: 6 },
{ label: 'Bananas', cost: 2 },
{ label: 'Coconuts', cost: 8 {
]
}
})
</script>

Dynamically Define HTML Attributes

There will be numerous occasions where you will want to define the attribute of an element by a data property rather than hardcoding it. This is where the  v-bind  directive comes in. An example is when you request data from an API and need to render data based on what is returned. Here is an example:

<div id="app">
<ul>
<li v-for="item in apiResponse">
<a v-bind:href="item.url">{{ item.name }}</a>
</li>
</ul>
</div>
<script>
const app = new Vue({
el: '#app',
data: {
apiResponse: [
{ name: 'GitHub', url: '<https://www.github.com>' },
{ name: 'Twitter', url: '<https://www.twitter.com>' },
{ name: 'Netlify', url: '<https://www.netlify.com>' }
]
}
})
</script>

Listening to Events and Responding to Them

When you want to listen to certain events on an element, Vue makes it easy for you to do this with the v-on directive.

A simple example of this is:

<div id="app">
<button v-on:click="alert('Hello!')">Click me!</button>
</div>

However, you will often want to call functions much more complex than a single line of JavaScript. And that's where methods come into play. Methods allow you to define functions that your Vue app will have access to. It is defined just like the  data  property.

const app = new Vue({
el: '#app',
data: {
favoriteColor: 'blue'
},
computed: {
label() {
return 'Color: ' + this.favoriteColor
}
},
methods: {
alertColor(color) {
alert('My favorite color is ' + color)
},
changeColor() {
console.log('I want to change my favorite color!')
}
}
})

As you can see, it takes an object that consists as any standard JavaScript function. However, there will be times where you want to interact with properties that are being managed in Vue (i.e., data, computed, other methods, etc.). Just like you would refer to  data  properties in  computed  values by prefixing it with  this, it is the same with everything else!

const app = new Vue({
el: '#app',
data: {
favoriteColor: 'blue'
},
computed: {
label() {
return 'color: ' + this.favoriteColor
}
},
methods: {
alertColor(colorLabel) {
alert('My favorite ' + colorLabel)
},
changeColor() {
// Changing a data property
this.favoriteColor = 'teal'
// Call a different method and passing a computed property
this.alertColor(this.label())
}
}
})

And with that, let's move on to inputs!

Update Data With Form Inputs

When working with form inputs, you may want to update the Vue data store so you can do things such as run validation, computations, etc. While you could manually do this yourself with a  v-on  directive with  v-bind, Vue provides a standard way to do this with  v-model. This allows you to define the data property that you want the form input to update as the user interacts with the form input. 

Here is an example:

<div id="app">
<label for="un">Username</label>
<input id="un" type="text" v-model="username" />
<label for="pw">Password</label>
<input id="pw" type="password" v-model="password" />
</div>
<script>
const app = new Vue({
el: '#app',
data: {
username: '',
password: ''
}
})
</script>

Now, whenever the user types in the respective input fields, the data store would be updated accordingly!

Exercise

You will find the source code for the exercises in the course's GitHub repo in the  cafe-with-a-vue folder. To get started, check out the  P1C4-Begin  branch.

Instructions

  1. Use  v-for  directive to render out all items from the data  simpleMenu  .

  2. Use  v-if  directive to show whether something is "In Stock" or "Out of Stock".

  3. Use  v-bind  to dynamically render each image in the menu and populate its  alt  text.

  4. Use  v-on  directive to increase the count of the shopping cart when adding an item from the menu with a function defined in methods called  addToShoppingCart.

  5. Use  v-model  to allow user to update how many items they want when adding to the shopping cart.

Let's Recap!

Congratulations! You have acquired abilities to utilize directives to:

  • Show and hide content.

  • Loop through a list of data and render its contents.

  • Dynamically update HTML attributes.

  • Listen for events that you can respond to.

  • Create JavaScript functions that Vue.js can use.

  • Configure form elements to update your data store as the user interacts with it.

It's time for us to review what you've learned in the course!

Example of certificate of achievement
Example of certificate of achievement