Let's learn the communication between VUE (14) components from scratch

The communication between components mainly includes the communication between parent and child components and the communication between sibling components . It is useful in the recent hand-practice project, record it as a memo

Parent-child component communication

Parent components can use custom properties to share data with child components props:["属性名"], and child components can send data to parent components through custom events. Parent-child communication can be easily realized by using custom attributes and custom events.
insert image description here

  • When modifying data, the subcomponent triggers a custom event through this.$emit('function name', passed value)
  • The @ binding event is used in the parent component, and the data passed from the child component to the parent component is received through val

Sibling communication

Using parent components as middleware

The simplest and crudest way to communicate with simple sibling components is to use two parent-child communications to realize the communication between brothers. Child component 1 sends data to the parent component through $emit, and the parent component will receive the data through custom attributes The data is passed to subcomponent 2.
insert image description here

Use EventBus

Steps for usage

  • Create eventBus.js module and share a Vue instance object (or define a new bus object and mount it on the prototype chain)
Vue.prototype.$bus = new Vue()
  • On the data sender, call bus.$emit('event name', the data to be sent) to trigger a custom event
this.$bus.$emit('getDetail', id)
  • On the data receiver, call bus.$on('event name', event handler function) to register a custom event
  created () {
    
    
    this.$bus.$on('getDetail', res => {
    
    
      this.goodsId = res
      console.log(res)
    })
  }

insert image description here

Use VueX

  1. Install the plugin:npm i vuex --save
  2. Create store.js
import Vue from 'vue'  
import Vuex from 'vuex'  
Vue.use(Vuex)  
  
export default new Vuex.Store({
    
      
  state:{
    
      
      queryId: '',
  },  
  mutations:{
    
      
    store_queryId(state, queryId) {
    
      
        state.queryId = queryId
    }
  }
})  
  1. Introduce and share the instance in main.js
import Vue from 'vue'
import App from './App.vue'
import store from './store'

new Vue({
    
    
    router,
    store,
    render: h => h(App)
  }).$mount('#app')

  1. data sender
this.$store.commit("store_queryId",queryId)
  1. data receiver
let queryId =  this.$store.state.queryId;

Guess you like

Origin blog.csdn.net/qq_46258819/article/details/126870247