最近学习Vue组件的时候遇到一个问题:
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. 组件模板应该包含一个根元素。
代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="app">
<timer></timer>
<timer></timer>
<timer></timer>
</div>
<template id="time">
<h2>当前数值为:{{counter}}</h2>
<button @click="counter++">+</button>
<button @click="counter--">-</button>
</template>
<script src="../js/vue.js"></script>
<script>
const obj = {
counter: 0
}
// 1.注册组件
Vue.component("timer",{
template: '#time',
data: function(){
return obj;
}
})
const app = new Vue({
el: '#app'
})
</script>
</body>
</html>
根据错误提示我将template标签中的内容包含在一个div标签中,错误解决
<template id="time">
<div>
<h2>当前数值为:{{counter}}</h2>
<button @click="counter++">+</button>
<button @click="counter--">-</button>
</div>
</template>