Single Root Element in Vue Components

While building your VueJS components. It’s important to note that you should have a Single Root Element as part of the Component template.

Let’s see what that means by and example.

We’ll build a very basic component that has an input box and below the input box, we show the user whatever he typed into the input box. Basic v-model binding.

Here is how the component looks

    Vue.component('input-binding',{
        template : `<input type="text" v-model="name"/> 
                        <p>Your Name is {{name}}</p>`,

        data() {
            return {
                name: 'Tushar',
            }
        } 
    });

Notice that we have used a literal string to define our template using the backtick. Along with this we also define a Basic Vue instance and mount it to the app id inside HTML.

We can now use the component element in our HTML.

    <div id="app">
          <input-binding></input-binding>
    </div>

This will not work and will throw the following error in your console.

This is because every Vue Component must have a single root element in its template. In our case we have two elements at the root one is input and another is p tag.

Fixing this is simple, you can wrap the whole template of a Component inside a div tag. In our case, we will modify our component to look like this.

    Vue.component('input-binding',{
        template : `<div>
                        <input type="text" v-model="name"/> 
                        <p>Your Name is {{name}}</p> 
                    </div>`,

        data() {
            return {
                name: 'Tushar',
            }
        } 
    });

That’s all about Components having Single Root Element in VueJS.

tgugnani: Web Stuff Enthusiast.