본문 바로가기
Web/JavaScript

[Vue3] Conditional Processing using v-if

by llHoYall 2021. 6. 8.

In Vue, we can conditional process using v-if, v-else-if, and v-else.

Create a Project

Let's create a project for a test.

2021.06.02 - [Web/JavaScript] - [Vue] Getting Started with Vue3 + TypeScript + TailwindCSS

Now, everything is ready.

Show/Hide Example using v-if

<h2 class="mb-2 text-xl font-medium text-green-600">if</h2>
<div v-if="varShow">This is a test string.</div>
<label
  ><input type="checkbox" v-model="varShow" class="mt-2 mr-2" />Show</label
>
data: function () {
  return {
    varShow: false,
  };
},

The test string will be show and hide according to the state of a checkbox.

Focus on the v-model and v-if.

 

There is exactly the same directive. That is v-show directive.

<div v-show="true">v-show test: true</div>
<div v-show="false">v-show test: false</div>

If v-show directive has true value, the associated HTML tag will be shown; otherwise, it will be hidden.

 

The operation results are the same in both cases.

However, there is a significant difference internally.

This is a result of an inspection.

In the v-if case, the tag itself is disappeared.

But, in the v-show case, the tag exists, but it is just not shown through CSS styling.

On/Off Example using v-if and v-else

<h2 class="mt-8 mb-2 text-xl font-medium text-green-600">if - else</h2>
<div v-if="varOnOff">On</div>
<div v-else>Off</div>
<label
  ><input type="checkbox" v-model="varOnOff" class="mt-2 mr-2" />On /
  Off</label
>
data: function () {
  return {
    varOnOff: false,
  };
},

If the value of the v-if directive is true, the associated HTML tag is valid; otherwise, the HTML tag corresponding to v-else directive is valid.

Select Example using v-if, v-else-if, and v-else

<h2 class="mt-8 mb-2 text-xl font-medium text-green-600">
  if - else-if - else
</h2>
<div>{{ varSelect }}</div>
<div v-if="varSelect === 'if'">Selected: if</div>
<div v-else-if="varSelect === 'else-if'">Selected: else-if</div>
<div v-else>Selected: else</div>
<select
  v-model="varSelect"
  class="mt-2 px-2 py-1 rounded text-gray-700 outline-none"
>
  <option>if</option>
  <option>else-if</option>
  <option>else</option>
</select>
data: function () {
  return {
    varSelect: "if",
  };
},

This is the same as a conditional statement in other programming languages.

You can easily understand this.

댓글