一、Vue.js組件化思想
Vue.js的核心思想之一就是組件化開發。組件系統是Vue的一個重要概念,它允許我們使用小型、獨立和通常可復用的組件構建大型應用。在Vue中,組件本質上是一個擁有預定義選項的Vue實例。
1.1 為什么需要組件化
- 代碼復用:避免重復造輪子,提高開發效率
- 可維護性:每個組件功能獨立,便于維護和測試
- 協作開發:不同開發者可以并行開發不同組件
- 清晰的結構:組件樹形式組織應用,結構一目了然
1.2 組件化開發原則
- 單一職責原則:一個組件只做一件事
- 高內聚低耦合:組件內部高度聚合,組件間盡量減少依賴
- 可組合性:組件可以嵌套使用形成更復雜的組件
- 明確的接口:通過props和events定義清晰的組件API
二、Vue組件基礎
2.1 組件注冊
全局注冊
Vue.component('my-component', {// 選項template: '<div>A custom component!</div>'
})
局部注冊
const ComponentA = { /* ... */ }
const ComponentB = { /* ... */ }new Vue({el: '#app',components: {'component-a': ComponentA,'component-b': ComponentB}
})
2.2 組件核心選項
Vue.component('example-component', {// 數據必須是一個函數data: function () {return {count: 0}},// props定義組件接收的屬性props: {title: String,likes: Number,isPublished: Boolean,commentIds: Array,author: Object,callback: Function,contactsPromise: Promise // or any other constructor},// 計算屬性computed: {reversedTitle: function () {return this.title.split('').reverse().join('')}},// 方法methods: {increment: function () {this.count += 1this.$emit('increment'