閱讀時間預估:2分鐘
前端
組件系統是 Vue 的另外一個重要概念,由於它是一種抽象,容許咱們使用小型、獨立和一般可複用的組件構建大型應用。仔細想一想,幾乎任意類型的應用界面均可以抽象爲一個組件樹,舉個栗子,就像小時候玩的積木同樣,想要一個好玩的玩具那麼就動手一個組件一個組件的拼接吧.vue
// 1 註冊全局組件
Vue.component('my-component', {
// template 只能有一個根元素
template: '<p>A custom component!</p>',
// 組件中的 `data` 必須是函數 而且函數的返回值必須是對象
data() {
return {
msg: '注意:組件的data必須是一個函數!!!'
}
}
})
// 2 使用:以自定義元素的方式
<div id="example">
<my-component></my-component>
</div>
// =====> 渲染結果
<div id="example">
<p>A custom component!</p>
</div>
// 3 template屬性的值能夠是:
- 1 模板字符串
- 2 模板id template: '#tpl'
<script type="text/x-template" id="tpl">
<p>A custom component!</p>
</script>
複製代碼
// 註冊組件,傳入一個擴展過的構造器
Vue.component('my-component', Vue.extend({ /* ... */ }))
// 註冊組件,傳入一個選項對象 (自動調用 Vue.extend)
Vue.component('my-component', { /* ... */ })
var Home = Vue.extend({
template: '',
data() {}
})
Vue.component('home', Home)
複製代碼
var Child = {
template: '<div>A custom component!</div>'
}
new Vue({
// 注意:此處爲 components
components: {
// <my-component> 將只在當前vue實例中使用
// my-component 爲組件名 值爲配置對象
'my-component': {
template: ``,
data () { return { } },
props : []
}
}
})
複製代碼
最後git
看完上面的代碼,對於善於利用腳手架開發的小夥伴來講是否是有一絲絲清涼,平時建立組件可不是這麼寫的,對於使用腳手架開發來講組件就是一個個Vue的實例,建立一個.vue文件,在須要用到的地方直接引用就OK了,確實是這樣的,那麼大俠,你可否在仔細深刻的研究下,腳手架是如何把各個組件關聯起來的呢?先留個懸念,後面會告訴你答案.程序員
若是個人分享對面前的這位大俠有所啓發,請不要吝嗇手中大拇指,以程序員最高禮遇點贊✨ 評論加分享的方式鼓勵我持續分享,也歡迎各位大佬勘誤,提出寶貴意見.github
關注公衆號回覆:學習 領取前端最新最全學習資料,也能夠進羣和大佬一塊兒學習交流bash