一、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'