vue.jseslint-plugin-vue

Problem "vue/no-multiple-template-root" occurs, how do I fix it?


Edit: Somehow doing v-if and v-else statements fixed this. Nonetheless could someone explain how to fix this?

Summary: Error occurs because of 2 Elements present in template. This Vue 3 The template root requires exactly one element.eslint-plugin-vue isn't helping. How do I fix this?

I'm currently following this tutorial (https://www.youtube.com/watch?v=72Fk9i9HcZM&t=830s) to create a Chat with Vue and Firebase. In the tutorial having two div-Elements is working w/o any issues. However, I tried it and it works but it is underlined in red and I ran into some issues later on. This is the Description of said problem:

[vue/no-multiple-template-root] The template root requires exactly one element.eslint-plugin-vue

I searched for some solutions and found this Vue 3 The template root requires exactly one element.eslint-plugin-vue. I tried the solutions provided but it doesn't solve the Problem.

This is my first time working with vue and eslint and I'm a beginner at programming. Could someone help me please?


Solution

  • In Vue 2 it was not allowed to have more than one root node inside a template.

    So this was allowed:

    <template>
       <div> <!--- this is a root node -->
           <p>This is content</p>
           <p>This is more content</p>
       </div>
    </template>
    

    But this is not allowed:

    <template>
       <div> <!--- this is a root node -->
           <p>This is content</p>
           <p>This is more content</p>
       </div>
       <div> <!-- error: this is a second root node -->
          <p> .... </p>
       </div>
    </template>
    

    You get a white screen and bells and whistles will go off in Developer Console if you do that.

    There was one exception though for root nodes that have v-if, v-else, v-else-if. The reasoning behind this is that, after evaluating these if statements there will be one only node that is mounted. This may be confusing to new users.

    So, to make it clear, this is allowed:

    <template>
       <div v-if="someExpression">
          <p>Case 1</p>
       </div>
       <div v-else-if="somethingElse">
         <p>Some other case</p>
       </div>
       <div v-else>
         <p>Else case</p>
       </div>
    </template>
    

    Vue 3 does allow muliple root nodes, so maybe your eslint rules are still vue 2 rules. Either way. For Vue it was recommended to always wrap the entire thing in tags just to be sure.

    Multiple root node errors are often caused by forgetting to properly close html tags, or use the wrong ones.