Frontend/Vue

Error : Component template should contain exactly one root element.

Mev01 2021. 5. 13. 01:30

Vue Component를 js파일로 따로 만드는 작업을 하고 있었습니다.

 

export default {
    template: `<div>사원목록</div>
    <div>
        <input type="text" name="name" id="name" ref="name">
        <button @click="search">검색</button>
    </div>
    <div>
        <table id="table">
            <tr>
                <th>아이디</th>
                <th>사원명</th>
                <th>부서</th>
            </tr>
            <tr v-for="emp in emps" v-if="emp.name.indexOf(name) != -1">
                <td>{{emp.id}}</td>
                <td>{{emp.name}}</td>
                <td>{{emp.dept}}</td>
            </tr>
        </table>
    </div>`,
    data() {
        return {
            emps : [],
            name : '',
        }
    },
    methods: {
        search() {
            this.name = this.$refs.name.value;
        },
    },
    mounted() {
        this.emps = JSON.parse(localStorage.getItem('emp'));
    },
};

그런데 이 js 파일을 import 하여 사용하던 도중 에러가 발생하였습니다.

Component template should contain exactly one root element. If you are using v-if on multiple elements, use v-else-if to chain them instead.

 

찾아보니 template은 하나의 root element를 사용하여야 한다고 말하고 있습니다.

즉, <div> </div>같은 element로 감쌀 필요가 있습니다.

 

template: `<div>
    <div>사원목록</div>
    <div>
        <input type="text" name="name" id="name" ref="name">
        <button @click="search">검색</button>
    </div>
    <div>
        <table id="table">
            <tr>
                <th>아이디</th>
                <th>사원명</th>
                <th>부서</th>
            </tr>
            <tr v-for="emp in emps" v-if="emp.name.indexOf(name) != -1">
                <td>{{emp.id}}</td>
                <td>{{emp.name}}</td>
                <td>{{emp.dept}}</td>
            </tr>
        </table>
    </div>
</div>`,

template부분을 이렇게 바꿔주니 문제가 해결되었습니다.

 

더 자세하게 알고싶으시면 Vue.js 문서를 참고하시면 좋습니다.

 

'Frontend > Vue' 카테고리의 다른 글

axios 사용법  (0) 2021.07.12
Vue 로컬 포트번호 변경  (0) 2021.07.12
d3js 사용법  (0) 2021.05.27
v-for와 v-if 분리하는 방법  (0) 2021.05.14