Join my Vue.js course while it's free 👀

Solve `'v-if' should be moved to the wrapper element` in Vue.js

April 5, 2022  ‐ 2 min read

When you use the eslint-plugin-vue package, which is the official ESLint plugin for Vue, to format your Vue code you will encounter some warnings and errors here and there. Such as the following one:

This 'v-if' should be moved to the wrapper element.

This error or warning occurs whenever you use both the v-for and v-if directive on the same HTML element. You might do so whenever you prefer to hide or not render the list based on a certain condition. As the warning suggest, the preferred way of doing this is by moving dat conditional to HTML element that contains the list with the v-for.

So instead of:

<!-- Vue ESLint doesn't like this -->
<template>
  <ul v-for="item in items" v-if="showItems">
    <li>{{ item }}</li>
  </ul>
</template>

The ESLint rule prefers this:

<!-- And prefers you to do this -->
<template>
  <div v-if="showItems">
    <ul v-for="item in items">
      <li>{{ item }}</li>
    </ul>
  </div>
</template>

Using v-show instead of v-if will not cause this warning as well. They do have different performance penalties you should be aware of.

<template>
  <ul v-for="item in items" v-show="showItems">
    <li>{{ item }}</li>
  </ul>
</template>

You can disable the [vue/no-use-v-if-with-v-for] rule all together by adding the following to the rules section of you ESLint config file:

'vue/no-use-v-if-with-v-for': 'off'

For more information, read the docs.