Vue conditional directives and loops

- Andrés Cruz

En español
Vue conditional directives and loops

In this entry, we are going to know how we can use conditionals and cycles, specifically the for in Vue; of course in the templates; the use of conditionals and cycles based on directives apply only to templates, since in handling scripts, you can use any of the primitives offered by vanilla JavaScript or pure JavaScript (without a framework).

Remember that an app in Vue consists of 3 blocks (optional):

  • template, for HTML,
  • script, for logic or JavaScript
  • style for the CSS.

The v-if directive

The v-if directive works as if it were a conditional, it allows evaluating true and false conditions that can be in functions, properties, etc.

    <input v-if="setDefaultValue" type="number" v-model="valor" />
    <div v-else-if="valor == 5">Los dioses me dicen que valor es 5</div>
    <div v-else>Ya no hay campo jaja</div>

As you can see; you can tie the else and the else if to it whose operation is the same as that of a conditional, therefore, you can nest conditions.

Here is the JavaScript block:

data() {
   return {
     valor: 0,
     setDefaultValue: true,
   };
 },

The v-for directive

With this directive we can iterate listings; that is, arrays:

    <div v-for="c in array" v-bind:key="c.id">
      <h3>{{ c.name }} {{ index }}</h3>
    </div>

Or the more complete way, with the index and the element:

    <div v-for="(c, index) in array" v-bind:key="c.id">
      <h3>{{ c.name }} {{ index }}</h3>
    </div>

Or with the array and/or based on components:

    <hello-world v-for="c in [1, 2, 3, 4, 5]" v-bind:key="c.id" />
    <br />

With loops in a nutshell, we can loop either an HTML tag or a Vue component multiple times.

Here is the JavaScript block:

data() {
   return {
     array: [
       {
         id: "123",
         name: "andres",
       },
       {
         id: "1234",
         name: "juan",
       },
     ],
   };
 },
Andrés Cruz

Desarrollo con Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz en Udemy

Acepto recibir anuncios de interes sobre este Blog.