通常一个应用会以一棵嵌套的组件树的形式来组织:
Vue组件化 - 图1
例如,你可能会有页头、侧边栏、内容区等组件,每个组件又包含了其它的像导航链接、博文之类的组件。

组件注册

全局注册

  1. Vue.component('my-component-name', {
  2. // ... 选项 ...
  3. })
  • 全局定义(Global definitions) 强制要求每个component中的命名不得重复
  • 字符串模板(String template)缺乏语法高亮,在HTML有多行的时候,需要用到丑陋的\
  • 不支持CSS (No CSS support)意味着当HTML和JavaScript组件化时,CSS明细被遗漏

局部注册

import ComponentA from './ComponentA'
import ComponentC from './ComponentC'

export default {
  components: {
    ComponentA,
    ComponentC
  },
  // ...
}

组件通信

父组件 => 子组件

  • 属性props

    // child
    props: {
    msg:    String
    }
    //parent
    <HelloWork msg="123456789" >
    

  • 引用refs

    //parent
    <HelloWork ref="hw" >
    //父组件先于子组件创建
    this.$refs.hw.xx = 'xx'
    
  • 子元素$children

    子元素顺序不定

//parent
this.$children[0].xx = 'xx'

子组件 => 父组件 :自定义事件

//child
this.$emit('add',good)

//parent
<Cart @add="cartAdd($event)"></Cart>

兄弟组件:通过共同父组件

通过共同组件搭桥,$parent或$root

// brother 1
this.$parent.$on('foo',handle)
// brother 2
this.$parent.$emit('foo')

祖先给后代传值

由于嵌套层数过多,传递props不切实际,vue提供了provide/injectAPI完成该任务

//ancestor
provide(){
  return     {foo:'foo'}
}
//descendant
inject:['foo']

注意:主要为高阶插件/组件库提供用例。并不推荐直接用于应用程序代码中。更多时候会在开源组件库中见到

任意两个组件之间:事件总线或vuex

  • 事件总线:创建一个Bus类负责事件派发、监听和回调管理
class Bus {
    construstor(){
      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')
  • vuex: 创建唯一的全局数据管理者store,通过他管理数据并通知组件状态变更

插槽

//comp2
<div>
  <slot></slot>
  <slot name="content"></slot>
  <slot name="content1" bla="1234"></slot>
</div>

//parent
<Comp2>
  //匿名插槽
  <template v-slot:default>12345</template>
  //具名插槽
  <template v-slot:content>65432</template>
  //作用域插槽
  <template v-slot:content1="slortPorps">{{slortPorps.bla}}</template>
</Comp2>