# vue组件化实践
# 组件化
vue组件系统提供了一种抽象,让我们可以使用独立可复用的组件来构建大型应用,任意类型的应用界 面都可以抽象为一个组件树。组件化能提高开发效率,方便重复使用,简化调试步骤,提升项目可维护 性,便于多人协同开发。

# 组件通信常用方式
# 1. props
父给子传值
// child
props: { msg: String }
// parent
<HelloWorld msg="Welcome to Your Vue.js App"/>
@前端进阶之旅: 代码已经复制到剪贴板
# 2. 自定义事件
子给父传值
// child this.$emit('add', good)
// parent
<Cart @add="cartAdd($event)"></Cart>
@前端进阶之旅: 代码已经复制到剪贴板
# 3. 事件总线
任意两个组件之间传值常用事件总线 或 vuex的方式。
// Bus:事件派发、监听和回调管理 class Bus {
constructor(){ this.callbacks = {}
}
$on(name, fn){
this.callbacks[name] = this.callbacks[name] || []
this.callbacks[name].push(fn) }
$emit(name, args){ if(this.callbacks[name]){
this.callbacks[name].forEach(cb => cb(args)) }
} }
// main.js
Vue.prototype.$bus = new Bus()
// child1
this.$bus.$on('foo', handle) // child2 this.$bus.$emit('foo')
