As we know, a large page in A VUE is made up of multiple sub-components, and the relationships between them are often complex, so understanding how components communicate becomes a top priority in a VUE. This article summarizes several communication methods in the VUE project.

Parent-child component communication

1.props/$emit

The parent component passes data to the child component via props, and the child component triggers the parent component’s methods via $emit to communicate with the parent

<! Parent component --> <template> <div class="parent"> <! -- via v-bind or":"The parent passes value--> <! -- passed in the child component$emitTrigger, parent component via V-ON or"@"Accept the emit method and then implement the child to parent data --> <child :myValue="value" @changeValue="changeValue"></child>
  </div>
</template>

<script>
import Child  from './Child'
export default {
  name: 'Parent',
  components: { Child  },
  data() {
    return {
      value: 'I'm going to pass it to the child.'
    }
  },
  methods:{
      changeValue(changedValue){
        this.value = changedValue
      }
  }
}
</script>

Copy the code
// Child child. vue <template> <div class="child" @click="emitParent">
    {{myValue}}
  </div>
</template>

<script>
import Child  from './Child'
export default {
  name: 'Child', props: {// Subcomponents accept myValue: String,},data() {
    return {
      
    }
  },
  methods:{
    emitParent(){// pass in the child component$emitTrigger, parent component via V-ON or"@"Accept the emit method and implement the child passing this to the parent data.$emit('changeValue', this.myValue + 1)
    }
  }
}
</script>
Copy the code

2.$parent/$children (not recommended)

Call this.$parent to get the parent (if any) of the current component, and call this.$children to get all of its children (if any), because this.$children is an array. You need to know the subscript for the location of the child component.

No special circumstances generally do not need to use, here only for understanding.

Non-parent component communication

1.provide/inject

Provide/Inject is a new API of VUE 2.2.0, which is mainly used for communication between parents, children, grandchildren, and all descendants. Provide specified properties in the parent component through the provide property, and inject the required properties in the desired descendant component (no matter how deep the component is nested).

For example

// Father.vue
<template>
  <div>
	<child></child>
  </div>
</template>

<script>
import Child from '.. /components/Child.vue'
export default {
  name: 'Father',
  provide: {
    for: 'demo'
  },
  components: {
    Child
  }
}
</script>

// Child.vue
<template>
  <div>
    {{for}}
  </div>
</template>

<script>
export default {
  name: 'Child',
  inject: ['for'],
}
</script>
Copy the code

2.ref/refs

Ref: Refers to the DOM element itself if used on a normal DOM element. If applied to a component element, points to an instance of the component. You can use the component’s data, methods, and so on through the this.$refs.ref attribute name.

Usage scenario: generally can be used for some pop-ups to show and hide.

// subcomponent a.ue <script>export default {
  data () {
    return {
      name: 'Vue.js'
    }
  },
  methods: {
    sayHello () {
      console.log('hello')
    }
  }
}
</script>
Copy the code
// Parent app.vue <template> <component-a ref="comA"></component-a>
</template>
<script>
  export default {
    mounted () {
      const comA = this.$refs.comA;
      console.log(comA.name);  // Vue.js
      comA.sayHello();  // hello
    }
  }
</script>
Copy the code

3.eventBus

EventBus, commonly known as the eventBus, can be used in vue as a bridge concept, as if all components share the same event center to which they can register to send and receive events, so that components can notify other components.

There are four main steps

  • To initialize eventBus, simply execute new Vue()
  • Import eventBus in the required components and emit events via eventbus.$emit().
  • Receive events via eventbus.$on() in the component that needs to receive them
  • EventBus.$off() to cancel the event
// create event-bus // event-bus.js import Vue from'vue'
export const EventBus = new Vue()
Copy the code
// In the required component$emit<template> <div> < button@click ="additionHandle"</button> </div> </template> <script> import {EventBus} from'./event-bus.js'
console.log(EventBus)
export default {
  data() {return{
      num:1
    }
  },

  methods:{
    additionHandle(){
      EventBus.$emit('addition', {
        num:this.num++
      })
    }
  }
}
</script>
Copy the code
/ / by$onReceive events // showNum. Vue receive events <template> <div> compute and: {{count}}</div> </template> <script> import {EventBus} from'./event-bus.js'
export default {
  data() {
    return {
      count: 0
    }
  },

  mounted() {
    EventBus.$on('addition', param => {
      this.count = this.count + param.num;
    })
  }
}
</script>
Copy the code
/ / by$offRemove the event import {eventBus} from'event-bus.js'
EventBus.$off('addition', {})
Copy the code

EventBus is generally used for systems with simple logic. If the logic is too complex, it is difficult to maintain eventBus. Vuex is generally recommended instead of eventBus.

4.vuex

Vuex is a state management mode that stores the common state of components and ensures state changes with corresponding rules. Vuex core is a store, it was quite a container, it contains a state, action, mutation, getter, core modules, etc

  • State: Used to store data and is the only data source in the store
  • Getters: Secondary wrapping based on state data, like computed properties in VUE, often used for filtering data and correlation calculation of multiple data
  • Mutations: similar to a function, the only way to change state data and cannot be used to handle asynchronous events
  • Actions: Similar to mutation, used to submit mutations to change state rather than directly change state, and can include arbitrary asynchronous operations
  • Modules: Similar to a namespace, used in a project to define and manipulate the state of modules separately for easy maintenance

Here is a simple example of VUex

const store = new Vuex.Store({ state: { count: 0 }, mutations: {increment (state) {state.count++}}}) {increment (state) {state.count++}}})"commit")
Copy the code

The most common vuEX scenarios are system messages and notifications. Or when multiple pages (components) share the same data.

To learn more about how to use vuex, refer to the article to understand how to use vuex