組件(Component)是 Vue.js 最強大的功能之一。
組件可以擴展 HTML 元素,封裝可重用的代碼。
在較高層面上,組件是自定義元素, Vue.js 的編譯器爲它添加特殊功能。
在有些情況下,組件也可以是原生 HTML 元素的形式,以 is 特性擴展。
當使用 DOM 作爲模版時(例如,將 el
選項掛載到一個已存在的元素上), 你會受到 HTML 的一些限制,因爲 Vue 只有在瀏覽器解析和標準化 HTML 後才能獲取模版內容。尤其像這些元素 <ul>
, <ol>
, <table>
, <select>
限制了能被它包裹的元素, <option>
只能出現在其它元素內部。
eg:
a不能包含其他的交互元素(比如按鈕,鏈接)
ul/ol只能包含li
select只能包含option和optgroup,
table只能包含thead,tbody,tfoot,tr,caption,col,colgroup,
tr只能包含th,td
違反這些規則,比如把<ul> <my-component>這種方式來組織,瀏覽器會把my-component提到元素的外面,導致渲染不正確。
<table> <tr is="my-component"></tr> </table>
在自定義組件中使用這些受限制的元素時會導致一些問題,例如:
<table>
<my-row>...</my-row>
</table>
自定義組件
<my-row>
被認爲是無效的內容,因此在渲染的時候會導致錯誤。變通的方案是使用特殊的 is
屬性:
<table>
<tr is="my-row"></tr>
</table>
應當注意,如果您使用來自以下來源之一的字符串模板,這些限制將不適用:
<script type="text/x-template">
- JavaScript內聯模版字符串
.vue
組件
因此,有必要的話請使用字符串模版。
組件分爲兩種:全局組件 和 局部組件
1、全局組件
全局組件的註冊須在初始化vue實例之前。
<div id="example">
<first-component></first-component>
</div>
// 註冊全局組件
Vue.component('first-component', {
template: '<div>This is my first component!</div>'
});
// 創建根實例
new Vue({
el: '#example'
});
渲染爲:
<div id="example">
<div>This is my first component!</div>
</div>
2、局部組件
局部組件可以通過使用某個vue組件實例註冊,
這樣可以使得註冊的組件只在當前vue實例的作用域有效。
var Child = {
template: '<div>This is my second component!</div>'
};
new Vue({
// ...
components: {
// <second-component>組件只在父模板可用
'second-component': Child
}
});