Extract Conditional Pattern

All quoted heavily from his article.

When we encounter a v-if (or v-show) in our template, there’s one main pattern we can use:

Extracting the body of each branch into its own component. – The Extract Conditional Pattern in Vue | Michael Thiessen

Pattern

We go from a code block like this:

<div v-if="condition">
  <div>
    <!-- Lots of code here -->
  </div>
</div>
<div v-else>
  <div>
    <!-- Lots of other code -->
  </div>
</div>

To this:

<div v-if="condition">
  <NewComponent />
</div>
<div v-else>
  <OtherComponent />
</div>

Why it works

We know we can do this for two reasons:

  1. Each branch is semantically related
  2. Each branch does distinct work

We know that each branch is semantically related, meaning all of that code works together to perform the same task.

Each branch also does distinct work — otherwise, why have a v-if at all?