为什么vuejs里面定义的template模板里定义的多个元素只显示一个

今天练习到vuejs组件这一块,组件是Vue.js最强大的功能之一,组件可以扩展HTML元素,封装可重用的代码。今天写了一段代码,开始显示的结果出现了错误,内容如下:

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<style type="text/css">
		#btn{
			background-color:green;
			color:white;
            font-family:"华文楷体";
            font-size:38px;
		}
	</style>
</head>
<body>
	<div id="app">
		<counter></counter>
		<counter></counter>
		<counter></counter>
		<counter></counter>
        </div>

    <template id="counter-template">
    	<h1>hello</h1>
    	<button id="btn">Submit</button>
    </template>
    <script type="text/javascript" src="vue.min.js"></script>
    <script type="text/javascript">
	    Vue.component('counter',{
		   template:'#counter-template'
	    });
	    new Vue({
		   el:"#app"
	    });
    </script>
</body>
</html>

结果在浏览器显示的结果如下图,不包含中在template中定义的按钮:

后来查找原因发现:vue2.x版本删除了多个节点的模板,目前每个组件必须只有一个根元素,建议将模板中的全部内容包装在一个新元素内。vue.js官网中的解释如下图:

修改代码,将代码中模板部分写成如下形式:

<template id="counter-template">
    	<div>
           <h1>hello</h1>
    	    <button id="btn">Submit</button>    		
        </div>
    </template>

显示预期的结果,如下图所示:

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章