vue组件通信(概念)

1.父组件=>子组件

  • 属性props
 // child
props:{msg:String}

// parent
<Helloworld msg='welcome to Vue'/>
  • 特性$attrs
// child 并未在props中声明foo
<p>{{$attrs.foo}}</p>

// parent
<helloworld foo="foo" />
  • 引用refs
// child
data(){return {xx: 'xxx'}}
// parent
<helloworld ref ='hw'/>
mounted(){this.$refs.hw.xx = 'xxxxxx'}
  • 子元素 ref
// parent $children中的子元素不保证顺序
mounted(){
  this.$children[0].xx = 'xxxxxx'
}

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

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

// parent
<Cart @add="add"></Cart>

3.兄弟组件之间传值

// brother1
this.$on('foo',handle) // 监听

// brother2
this.$emit('foo') //发起事件

4.祖先和后代之间

由于嵌套层数过多.props不切实际,vue 提供了 provide/inject api完成任务
    // ancestor
provide(){
  return {
   foo: 'foo'
 }
}

//  descendant
inject:{
    foo: ''
}

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

1.事件总线:创建一个Bus类负责事件派发、监听和回调管理(实践中可以用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.protype.$bus = new Bus()

// child1
this.$bus.$on('foo',handle)

//child2
this.$bus.$emit('foo')

2.vuex: 创建唯一的全局数据管理者store,通过他管理数据并通知组件状态变更
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容