Vue组件化

90 阅读1分钟
  1. 组件通信方式盘点
  2. 组件复合
  3. 递归组件
  4. 组件构造函数和实例
  5. 渲染函数
  6. 组件挂载

组件化

image.png

组件通信

props

父给子传值


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

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

事件总线

// 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')

实践中通常用Vue代替Bus,因为Vue已经实现了相应接口

vuex

创建唯一的全局数据管理者store,通过它管理数据并通知组件状态变更

parent/parent/root

兄弟组件之间通信可通过共同祖辈搭桥,parentparent或root。

// brother1
this.$parent.$on('foo', handle) 
// brother2
this.$parent.$emit('foo')

$children

父组件可以通过$children访问子组件实现父子通信。

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

注意:$children不能保证子元素顺序

attrs/attrs/listeners

包含了父作用域中不作为 prop 被识别 (且获取) 的特性绑定 ( class 和 style 除外)。当一个组件没有 声明任何 prop 时,这里会包含所有父作用域的绑定 ( class 和 style 除外),并且可以通过 vbind="$attrs" 传入内部组件——在创建高级别的组件时非常有用。

// child:并未在props中声明foo

    {{$attrs.foo}}

// parent

文档

refs

获取子节点引用

// parent 
mounted() {
    this.$refs.hw.xx = 'xxx'
}

provide/inject

能够实现祖先和后代之间传值

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

插槽

插槽语法是Vue 实现的内容分发 API,用于复合组件开发。该技术在通用组件库开发中有大量应用。

匿名插槽

// comp1
<div>
    <slot></div>
// parent 
<comp1>hello</comp1>

具名插槽

将内容分发到子组件指定位置

    // comp2
<div>
    <slot/>
    <slot name="content"></slot>
</div>
// parent 
// 默认插槽用default做参数
<comp2>
    <template v-slot:default>hello</template>
    <template v-slot:content>内容</template>
</comp2>    

作用域插槽

分发内容要用到子组件中的数据

    // comp3
<div>
    <slot :foo="foo"/>
</div>
// parent 

<comp3>
    <template v-slot:default="slotProps">
        {{slotProps.foo}}
    </template>
</comp2>