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')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值