Vue.js 基礎學習之混合mixins
阿新 • • 發佈:2017-09-05
sda itl 實現 var title cte 混合 method ons
混合以一種靈活的方式為組件提供分布復用功能。混合對象可以包含任意的組件選項。當組件使用了混合對象時,混合對象的所有選項將被“混入”組件自己的選項中。
當混合對象與組件包含同名選項時,這些選項將以適當的策略合並。例如,同名鉤子函數被並入一個數組,因而都會被調用。另外,混合的鉤子將在組件自己的鉤子之前調用。
我自己的理解是:混合就是將一些相似組件的相同部分用一個對象封裝起來,實現代碼的復用。當然如果在組件中重新定義某些東西就會覆蓋掉來自混合的相應部分。
混合的使用:首先將公共部分寫入一個對象,在組件中添加 mixins屬性 ,並且這個屬性的值是一個數組,數組中就是混合對象。
如:var base = {}; 在組件中: mixins : [base],
<div id="app"> <show-hide-title></show-hide-title> <show-hide-content></show-hide-content> </div>
<script> var base = { data : function(){ return { visible : false, }; }, methods : { show :function(){ this.visible = true; }, hide : function(){ this.visible = false; }, toggle :function() { this.visible = !this.visible; } } }; Vue.component(‘show-hide-title‘,{ template : `<div> <span @mouseenter=‘show‘ @mouseleave=‘hide‘>鼠標移入顯示/移出隱藏標題</span> <h1 v-if=‘visible‘>這是標題</h1> </div> `, mixins : [base], }); Vue.component(‘show-hide-content‘,{ template :` <div> <button @click=‘toggle‘>顯示/隱藏內容</button> <div v-if="visible"> <p><a @click=‘hide‘ href="#">關閉內容</a></p> 這是內容Lorem ipsum dolor sit amet, consectetur adipisicing elit. Alias quibusdam eligendi dolor,
mollitia animi maiores, quod saepe dolores! Dolorum non porro iusto quod facere consequuntur
dolorem reprehenderit, cumque reiciendis sit. </div> </div> `, mixins : [base], }); new Vue({ el: ‘#app‘, }); </script>
以上代碼中兩個組件一個是通過鼠標的移入與移出來控制標題的顯示與隱藏,另一個是通過點擊按鈕來控制內容的顯示與隱藏,他們有一部分公共內容用base封裝起來,分別在兩個組件中加入混合就可以了。
Vue.js 基礎學習之混合mixins