### 什么是Vue.extend?
Vue.extend 返回的是一個“擴展實例構造器”,也就是預設了部分選項的Vue實例構造器。經常服務于Vue.component用來生成組件,可以簡單理解為當在模板中遇到該組件名稱作為標簽的自定義元素時,會自動調用“擴展實例構造器”來生產組件實例,并掛載到自定義元素上。
由于我們還沒有學習Vue的自定義組件,所以我們先看跟組件無關的用途。
### 自定義無參數標簽
我們想象一個需求,需求是這樣的,要在博客頁面多處顯示作者的網名,并在網名上直接有鏈接地址。我們希望在html中只需要寫<author></author> ,這和自定義組件很像,但是他沒有傳遞任何參數,只是個靜態標簽。
我們的Vue.extend該登場了,我們先用它來編寫一個擴展實例構造器。代碼如下:
~~~javascript
var authorExtend = Vue.extend({
template:"<p><a :href='authorUrl'>{{authorName}}</a></p>",
data:function(){
return{
authorName:'bizzbee',
authorUrl:'http://www.baidu.com'
}
}
});
~~~
這時html中的標簽還是不起作用的,因為擴展實例構造器是需要掛載的,我們再進行一次掛載。
`new authorExtend().$mount('author');`
這時我們在html寫<author><author>就是管用的。我們來看一下全部代碼:
~~~html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="../assets/js/vue.js"></script>
<title>vue.extend-擴展實例構造器</title>
</head>
<body>
<h1>vue.extend-擴展實例構造器</h1>
<hr>
<author></author>
<script type="text/javascript">
var authorExtend = Vue.extend({
template:"<p><a :href='authorUrl'>{{authorName}}</a></p>",
data:function(){
return{
authorName:'JSPang',
authorUrl:'http://www.jspang.com'
}
}
});
new authorExtend().$mount('author');
</script>
</body>
</html>
~~~
### 掛載到普通標簽上
還可以通過HTML標簽上的id或者class來生成擴展實例構造器,Vue.extend里的代碼是一樣的,只是在掛載的時候,我們用類似jquery的選擇器的方法,來進行掛載就可以了。
~~~javascript
new authorExtend().$mount('#author');
~~~