1.簡單介紹
Vue.extend(options)
參數:對象
用法:使用Vue構造器,創建一個“子類”,參數是一個包含組件選項的對象,其中,data
選項中必須是函數
描述:Vue.extend
返回的是一個“擴展實例構造器”,也就是預設了部分選項的Vue的實例構造器,它常常服務于Vue.component
用來生成組件,可以簡單理解為當在模板中遇到該組件作為標簽的自定義元素時,會自動調用“擴展實例構造器”來生產組件實例,并掛在到自定義元素上
2.簡單舉例
自定義無參數標簽
下面的代碼中的author就是返回的“擴展實例構造器”
var author = Vue.extend({template: "<p><a :href='url'>{{author}}</a></p>",data : function() {return {author : 'vamous',url : 'http://blog.csdn.net/Dear_Mr/article/details/72614370'}}
});
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
對應的html如下:
<author></author>
- 1
此時的頁面必然是沒有任何效果的,因為擴展實例構造器還需要掛載,如下
new author().$mount('author');
- 1
使用propsData
var author = Vue.extend({template: "<p><a :href='url'>{{author}} & {{name}}</a></p>",data : function() {return {author : 'vamous',url : 'http://blog.csdn.net/Dear_Mr/article/details/72614370'}},props : ['name']
});new author({propsData: {name : 'dear_mr'}}).$mount('#author');
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
可以利用propsData傳遞參數
掛載在普通標簽上
返回的擴展實例構造器的方式和上面還是一樣的,只是html里不再是自定義標簽,而是一個普通標簽,比如div
<div id="author"></div>
- 1
new author().$mount('author');
- 1
其實對于同一個擴展構造器而言,它的每一個實例其實是可以掛載到不同的標簽上的,比如我可以這樣
new author().$mount('#author');
new author().$mount('author');
- 1
- 2
這兩個標簽的內容會一同顯示,結果一樣