组件系统是 Vue 的一个重要概念,因为它是一种抽象,允许我们使用小型、独立和通常可复用的组件构建大型应用。几乎任意类型的应用界面都可以抽象为一个组件树。组件化能提高开发效率,方便重复使用,简化调试步骤,提升项目可维护性,便于多人协同开发。
组件通信
props
父给子传值
// 父组件
<HelloWorld msg="Welcome to Your Vue.js App"/>
// 子组件
props: {
msg: String }
自定义事件
子给父传值
// 父组件
<Cart @onAdd="cartAdd($event)"></Cart>
// 子组件
this.$emit('onAdd', data)
事件总线
任意两个组件之间传值,Vue
中已经实现相应接口,下面是实现原理,其实也是典型的发布-订阅模式。
// 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()
// 组件1
this.$bus.$on('add', handle)
// 组件2
this.$bus.$emit('add')
vuex
任意两个组件之间传值,创建唯一的全局数据管理者store,通过它管理数据并通知组件状态变更。vuex官网
$parent/$roots
兄弟组件之间通信可通过共同祖辈搭桥, $parent
或 $root
。
// 兄弟组件1
this.$parent.$on('foo', handle)
// 兄弟组件2
this.$parent.$emit('foo')
$children
父组件可以通过 $children
访问子组件实现父子通信。
// 父组件
this.$children[0].xx = 'xxx'
需要注意
$children
并不保证顺序,也不是响应式的。
$attrs/$listenners
$attrs
包含了父作用域中不作为 prop 被识别 (且获取) 的 attribute 绑定 (class
和 style
除外)。
// 父组件
<HelloWorld foo="foo"/>
// 子组件:并未在props中声明foo
<p>{
{ $attrs.foo }}</p>
$listenners
包含了父作用域中的 (不含 .native
修饰器的) v-on
事件监听器。
// 父组件
<HelloWorld v-on:event-one="methodOne" />
// 子组件
created() {
console.log(this.$listeners) // { 'event-one': f() }
}
$refs
一个对象,持有注册过 ref
attribute 的所有 DOM 元素和组件实例。
<HelloWorld ref="hw" />
mounted() {
this.$refs.hw.xx = 'xxx'
}
provide/inject
以允许一个祖先组件向其所有子孙后代注入一个依赖。
// 祖先组件提供
provide () {
return {
foo: 'bar' }
}
// 后代组件注入
inject: ['foo&