爲什麼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>

顯示預期的結果,如下圖所示:

 

 

 

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