注意:無論哪種定義方式,組件的要標簽只能有1個,多余的不會顯示也不報錯,默認顯示第一個標簽
vue創建組件的三種方式:
第一種:
<div id="app"> <com1></com1> </div> <script> var com1 = Vue.extend({ template: '<div>com1 組件</div>' }); Vue.component('com1', com1); new Vue({ el: '#app', }); </script>
第二種:
<div id="app"> <com1></com1> </div> <script> Vue.component('com1', Vue.extend({ template: '<h1>com1組件</h1>' })); //或者 // Vue.component('com1', { // template: '<h1>com1組件</h1>' // }); new Vue({ el: '#app', }); </script>
第三種:
<div id="app"> <com1></com1> </div> <template id="tpl"> <div><h1>使用template元素創建的組件</h1></div> </template> <script> Vue.component('com1', { template: '#tpl' }); new Vue({ el: '#app', }); </script>
定義私有組件:
<div id="app"> <com2></com2> </div> <script> new Vue({ el: '#app', components: { com2:{ template: '<h2>這是私有組件</h2>' } } }); </script>