上篇也总结了一下vue组件中的传值方式,父子组件,兄弟组件,隔代组件等,这篇总结了事件总线 Bus,
vuex(简单的了解了一下,具体写法看官网:vuex.vuejs.org/),插槽的用法。
原文:www.cnblogs.com/yearshar/p/…
任意两个组件之间:事件总线 或 vuex
事件总线: 创建一个Bus负责事件预发,监听和回调管理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | //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.callback[name].forEach(cb=>cb(args)) } }}<br><br>//main.js<br> Vue.prototype.$bus=new Bus()<br> <br>//child1<br>this.$bus.$on('foo',handle)<br><br>//child2<br>this.$bus.$emit('foo')<br><br>ps:实践中可以用Vue代替Bus。因为它已经实现了相应功能 |
Vuex:创建唯一的全局数据管理者store,通过它管理数据并通知组件状态变更
插槽
插槽语法是Vue实现的内容分发API,用于复合组件开发,该技术在通用组件库开发中有大量应用
vue2.6.0之后采用全新v-slot语法取代之前的slot,slot-scope
匿名插槽
1 2 3 4 | //child 子组件会将父组件提供的内容分发 <p> <slot></slot></p><br><br><br>//parent 父组件提供内容<br> <child>hello</child> |
具名插槽
将内容分发到子组件指定位置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | //child <div> <slot></slot> <slot name="centent"></slot> </div>//parent <child> <!--默认插槽用default做参数--> <template v-slot:default>具名插槽</template> <!--具名插槽用插槽名做参数--> <template v-slot:centent>内容……</template> </child><br> |
作用域插槽
分发内容要用到子组件中的数据(数据来自子组件,需要在父组件中进行加工)
1 2 3 4 5 6 7 8 9 10 | //child<div> <slot :foo="foo"></slot></div> //parent <child> <template v-slot:default="slotProps"> 来自子组件数据:{{slotProps.foo}} </template><br><br> <strong><!--可以直接解构--></strong> |
1 | <template v-slot:default="{foo}"> 来自子组件数据:{{foo}} </template> |
1 | </child> |