將頁面拆分為多個組件,簡化了頁面開發,方便維護,組件也可以復用,
組件的型別
- 通用組件,比如表單、彈窗、選單欄、分頁組件等
- 業務組件,實作某一業務的組件,比如抽獎組件
- 頁面組件,也叫做單頁,一個頁面就是一個組件,只完成功能,不復用
組件開發流程:宣告、注冊、使用
demo 組件使用流程
<div id="app"></div> <script> var myHeader={ //宣告一個組件 template:'<div>this is the header area</div>' } var myBody={ template:'<div>this is the body area</div>' } var myFooter={ template:'<div>this is the footer area</div>' } new Vue({ el:'#app', components:{ //注冊組件 myHeader, myBody, myFooter }, template:'<div><myHeader></myHeader><myBody></myBody><myFooter></myFooter></div>' //使用組件 }); </script>
宣告是全域宣告,但需要在每一個使用Vue物件中進行注冊,
使用組件有2種方式
- <myHeader></myHeader> 直接以變數名作為標簽名
- <my-header></my-header> 單詞都轉換為全小寫,-連接
宣告組件時是用了語法糖的
// 原來的寫法 var myHeader=Vue.extend({ template:'<div>this is the header area</div>' }) // 語法糖 var myHeader={ template:'<div>this is the header area</div>' }
效果都一樣,但使用語法糖明顯要簡便些
組件宣告、注冊的另一種方式
// 宣告+注冊一個組件 Vue.component('MyHeader',{ template:'<div>this is the header area</div>' }) Vue.component('MyBody',{ template:'<div>this is the body area</div>' }) Vue.component('MyFooter',{ template:'<div>this is the footer area</div>' }) new Vue({ el:'#app', template:'<div><my-header></my-header><my-body></my-body><my-footer></my-footer></div>' //使用組件 });
宣告、注冊都是全域的,在Vue物件中可以直接使用
組件中除了template,還可以有其它部分,比如data,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/137748.html
標籤:JavaScript
上一篇:[前端] 代碼中執行系結元素的指定事件trigger方法
下一篇:Vue 向組件中插入內容
