vue组件传值、通信

vue组件传值、通信

父组件--------》子组件
属性
// parent
<HelloWorld msg="Welcome to Your Vue.js App"/>

// child
props: { msg: String }
引用refs
// parent
<HelloWorld ref="hw"/>

修改子组件的值
this.$refs.hw.xx = 'xxx'
子组件chidren
// parent 
this.$children[0].xx = 'xxx'
子组件---->父组件
自定义事件
// parent
<Cart @add="cartAdd($event)"></Cart>

// Cart.vue 
this.$emit('add', good)
兄弟组件
通过共同的父辈
// brother1 
	this.$parent.$on('foo', handle)
// brother2 
	this.$parent.$emit('foo')
祖先和后代之间
// ancestor 
provide() {
 return {foo: 'foo'}
}
// descendant 
inject: ['foo']

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

// Bus:事件派发、监听和回调管理class Bus{
constructor(){
// {
//	eventName1:[fn1,fn2],
//	eventName2:[fn3,fn4],
// } 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')
原文地址:https://www.cnblogs.com/cupid10/p/15617600.html