關(guān)鍵詞:構(gòu)建組件
引入vue.js
* <script src="https://unpkg.com/vue/dist/vue.js"></script>
全局組件
Vue.component('m-title', {
template:`<div>welcome to ferrinte blog</div>`
});
模板方式搭建
// 模板(寫在script標(biāo)簽外)
<template id="title">
<div>
<h1>風(fēng)景</h1>
<p>洛陽城里花如雪</p>
<p>洛陽花開動京城</p>
</div>
</template>
<script type="text/javascript">
Vue.component('m-title', {
template:'#title'
});
注冊使用
new Vue({
el: '#demo',
});
<div id="demo">
<m-title></m-title>
</div>
<m-title></m-title> <!-- 無效 -->
注意
- 組件只能有一個根元素
- 全局組件代碼一定要在注冊代碼之前
- 全局組件不注冊無法使用
- 組件中的data必須是函數(shù)
局部組件
var Child = {
template: '<div>你見或者不見我,我就在那里,不離不棄</div>'
}
new Vue({
// ...
components: {
// <my-component> 將只在父模板可用
'my-component': Child
}
})
這種封裝也適用于其它可注冊的 Vue 功能狗热,如指令序无。
DOM 模版解析說明
當(dāng)使用 DOM 作為模版時(例如,將 el選項掛載到一個已存在的元素上), 你會受到 HTML 的一些限制涉茧,因為 Vue 只有在瀏覽器解析和標(biāo)準(zhǔn)化HTML 后才能獲取模版內(nèi)容。尤其像這些元素
* <ul>,<ol>迎膜,<table>,<select>
限制了能被它包裹的元素浆兰, <option>只能出現(xiàn)在其它元素內(nèi)部磕仅。
這種方式是無效的
<table>
<my-row>...</my-row>
</table>
應(yīng)該這樣寫
<table>
<tr is="my-row"></tr>
</table>
如果您使用來自以下來源之一的字符串模板,這些限制將不適用:
- <script type="text/x-template">
- JavaScript內(nèi)聯(lián)模版字符串
- .vue 組件