总的来说,做前端已经有大概两年了。想往web全栈的方向发展一下,结果去网上找了一些资源,听完课被虐的体无完肤。今天就给大家分享一下组件的通信方式吧。
-
props
-
eventbus
-
vuex
事件:
1.$parent
2.$childern
3.$root
4.refs(这个应该是大家比较常用的)
5.provide/inject (事件注入,用于祖先对后代的数据传递)
组件通信:
-
props(父传子)
//子 props:{msg:String} //父 <Parent msg=",人狠话不多,我是你爸爸"></Parent>
-
自定义事件
//子 this.$emit('add',good) //父 <Parent @add="sonAdd($event)"></Parent>
-
事件总线
事件总线主要是用于任意组件之间传值,和VueX的方式相同。
//事件派发,监听,回调 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(item=>{item(args)}) } } } //main.js Vue.prototype.$bus = new Bus() //子n this.$bus.$on('foo',handle) //子n+1 this.$bus.$emit('foo')
-
VueX
至于VueX大家可以去官网看一下官方文档。这里就不在赘述。
-
$parent/$root
//brother1 this.$parent.$on('foo',handle) //brother2 this.$parent.$emit('foo')
-
$children
//父组件可以通过$children来访问子组件 this.$children[n].xx = '***' 但是这个n并不是按照组件在dom中的先后顺序来确定的,这个值不大确定
-
$refs 这个也不说了,这个估计大家用的和熟悉了
说一句吧,有时候通过$refs.XXXX获取数据,可能会是undefined ,
//通过这种方式获取就可以了 this.$nextTick(()=>{ this.$refs.XXX })
-
provide/inject
这是可以实现祖先和任意后代传值的
//祖先 provide(){ return{foo:'foo'} } //后代 inject:['foo']
最近在研究组件的封装,以及各大框架的源码,有兴趣的可以在评论下面大家一起研究。