6 Ways Components Communicate


foreword

提示:这里可以添加本文要记录的大概内容:

There are roughly 6 commonly used component communication methods in vue projects: props, custom events, global event bus $bus, pubsub-js, Vuex, slots


One, props

  1. Applicable scenario: parent-child component communication
  2. Note:
    2.1 If the parent component passes data (function) to the child component: the essence is that the child component passes data to the parent component.
    2.2 If the parent component passes data to the child component (not a function): the essence is that the parent component passes data to the child component.
  3. Writing method: There are 3 types
    3.1 Array form: [ 'todos' ]
    3.2 Object form (declared data type): { type:String }
    3.3 Object form (declared data type, default value...): age: { type: Number,default : 20 }
  4. Routing props writing form: There are 3 types
    4.1 Boolean value props: false (default false)
    4.2 Object {props: {id: 666, msg: 'abc'}
    4.3 Function form props($route) { return {id: $route .query.id,msg: $route.query.msg}

2. Custom events

  1. Applicable scenario: child components pass data to parent components
  2. The main method $on binds custom events. , $emit triggers a custom event, $off unbinds a custom event

3. Global event bus $bus

  1. Applicable scenarios: universal, father-son and brother components are all available
  2. Just install it in the main.js file
new Vue({
    
    
  render: h => h(App),
  // 安装全局事件总监
  beforeCreate() {
    
    
    Vue.prototype.$bus = this
  }
}).$mount('#app')  			

Four, pubsub-js publish and subscribe

  1. Applicable scenarios: universal, father-son and brother components are all available
  2. It is used more in the React framework
import pubsub from 'pubsub-js'

5. Vuex

  1. Use scene: universal

6. Slot

  1. Applicable scenario: parent-child component communication - general transmission structure
  2. Three kinds of slots
    2.1 Default slot
    2.2 Title slot
    2.3 Scope slot

Guess you like

Origin blog.csdn.net/weixin_46278178/article/details/127667545