vue组件中的几种传值方式----下篇

上篇也总结了一下vue组件中的传值方式,父子组件,兄弟组件,隔代组件等,这篇总结了事件总线 Bus,

vuex(简单的了解了一下,具体写法看官网:https://vuex.vuejs.org/),插槽的用法。

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

 事件总线: 创建一个Bus负责事件预发,监听和回调管理

//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))
   }
 }
}

//main.js
Vue.prototype.$bus=new Bus()

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

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

ps:实践中可以用Vue代替Bus。因为它已经实现了相应功能

  

Vuex:创建唯一的全局数据管理者store,通过它管理数据并通知组件状态变更

插槽

插槽语法是Vue实现的内容分发API,用于复合组件开发,该技术在通用组件库开发中有大量应用

vue2.6.0之后采用全新v-slot语法取代之前的slot,slot-scope

匿名插槽

  

//child  子组件会将父组件提供的内容分发
 <p>
  <slot></slot>
</p>


//parent 父组件提供内容
<child>hello</child>

  具名插槽

将内容分发到子组件指定位置

//child
 <div>
  <slot></slot>
  <slot name="centent"></slot>
 </div>



//parent
  <child>
  <!--默认插槽用default做参数-->
    <template v-slot:default>具名插槽</template>
  <!--具名插槽用插槽名做参数-->
    <template v-slot:centent>内容……</template>
  </child>

  

作用域插槽

分发内容要用到子组件中的数据(数据来自子组件,需要在父组件中进行加工)

//child
<div>
    <slot :foo="foo"></slot>
</div>    

//parent
 <child>
  <template v-slot:default="slotProps">
   来自子组件数据:{{slotProps.foo}}
  </template>

<!--可以直接解构-->
<template v-slot:default="{foo}"> 来自子组件数据:{{foo}} </template>
 </child>

  

猜你喜欢

转载自www.cnblogs.com/yearshar/p/11954210.html