Communication between Vue components -- collation

Posted by Lil Smurth on Tue, 25 Jan 2022 08:18:20 +0100

Vue inter component communication

Several scene previews

  • Data transfer between parent and child components
  • Data transfer between sibling components
  • Data transfer between ancestor components and subcomponents
- props / $emit
- $parent / $children and ref
- $emit / $on
- vuex
- $attrs / $listeners
- provide / inject

Several component communication methods are better selected

  • When the project is large, use vuex
  • Use $parent and $children sparingly. Their purpose is to serve as an emergency method for accessing components. It is more recommended to use props and events to realize parent-child component communication
  • If you are just passing data, use a t t r s / attrs/ attrs/listeners better
  • If you not only transfer data, but also do intermediate processing, vuex is better

Method 1: props/$emit

  • Parent component A passes data to child component B through props method
  • Child component B sends data to parent component A through emit

Father -- son
sonList: ['white','red','blue','green']

Parent component

<template>
    <div class="father">
        <com-son :sons="sonList"></com-son>
    </div>
</template>

<script>
    import comSon from './son'
    export default {
        name:"helloworld",
        components: {comSon},
        data(){
            return {
                sonList: ['white','red','blue','green']
            }
        }
    }
</script>

Sub assembly son vue

<template>
  <div>
    <span v-for="(item, index) in sons" :key="index">{{item}}</span>
  </div>
</template>

<script>
export default {
  props: ['sons']
}
</script>

be careful:

  • One way data flow refers to the transfer of sub components from the upper level component to the lower level component, that is, parent-child components
  • props is read-only and cannot be modified. All modifications will be invalidated and warned

The child component passes data to the parent component

Parent component father vue

<template>
  <div class="father">
    <com-son :sons="sonList" @onEmitIndex="onEmitIndex"></com-son>
    <p>{{currentIndex}}</p>
  </div>
</template>

<script>
import comSon from './son'
export default {
  name: 'HelloWorld',
  components: { comSon },
  data() {
    return {
      currentIndex: -1,
      sonList: ['Xiaobai', 'Xiao Hong', 'Blue ','Little green']
    }
  },
  methods:{
    onEmitIndex(idx){
      this.currentIndex = idx
    }
  }
}
</script>

Sub assembly son vue

<template>
  <div>
    <span v-for="(item, index) in sons" :key="index" @click="emitIndex(index)">{{item}}</span>
  </div>
</template>

<script>
export default {
  props: ['sons'],
  methods: {
    emitIndex(index){
      this.$emit('onEmitIndex',index)
    }
  }
}
</script>

Why use vuex

Without vuex

  • Parent and child components depend on the same state

  • Sibling components depend on the same state

    vuex was used

Vuex modules

state

state The status field in which the page share is stored

getters

Equivalent to current module state Calculated properties of

mutations

If you want to update state Fields in, submitting mutations The only way to define events in( key Is the event name, value Is a function), but change Event functions must be executed synchronously

actions

Asynchronous functions can be defined and submitted in callback functions mutation,It is equivalent to asynchronous update state Fields in

modules

Similar to namespace( namespace),It is used to define and operate the status of each module in the project separately for easy maintenance

$attrs / $listeners

It is used in the parent component to transfer data to child components or grandchildren

If it's just passing data, use $attrs / $listeners Better

How to not only transfer data, but also do intermediate processing, just use vuex Better

$attrs:

  • $attrs inherits all parent component attributes (except the attributes passed by props, class and style)
  • When a component does not declare any prop, all parent scopes will be included here

$listeners

  • An object that contains the v-on event listeners in the parent scope. It can cooperate with v-on="$listeners" to point all event listeners to specific child elements

summary

The communication between vue components can be roughly divided into three categories

Father son communication

props/emit, parent/children, attrs/$listeners, provide/inject API, ref

Pass data from parent to child props

Pass from child to parent $emit, event

The child instance accesses the parent instance through $parent

Parent instance accesses child instance through $children

$attrs Use the parent component to pass data to the child component or grandchild component
(Contains no actions in the parent scope prop Identified (And get) Property binding for (class and style except))

listeners Use the parent component to pass data to the child component or grandchild component
 Contains the in the parent scope (Not included .native Modifier) v-on Event listener

Ancestor component pass provider Provide variables to child components

Descendant component pass inject Inject variables into ancestor components

ref Used to access component instances

Brother communication

vuex is used for communication between brothers and across levels

Cross level communication

Vuex, attrs/listeners, provide/inject API

vuex As communication between brothers and across levels

$attrs Use the parent component to pass data to the child component or grandchild component
(Contains no actions in the parent scope prop Identified property binding( class and style Except)

listeners Use the parent component to pass data to the child component or grandchild component
 Contains (excluding) in the parent scope.native Modifier) v-on Event listener

Ancestor component pass provider Provide variables to child components

Descendant component pass inject Inject variables into ancestor components

  • The parent component transfers data to the child component, and uses props attribute; The child component transmits data to the parent component, uses $emit to dispatch events in the child component, and uses v-on to listen to events in the parent component;
    • Disadvantages: if there are many nested levels of components, it is troublesome to transfer data.
  • The ancestor component transmits data to all its descendants by means of dependency injection / provide;
    • Disadvantages: the source of data modification cannot be monitored, and the response type is not supported.
  • Access the data in the root component, parent component and child component through the attribute $root / $parent / $children / ref
    • Disadvantages: the response type is not supported and vue2 has been abandoned
  • Vuex, the state management mode of VueJs, enables data sharing among multiple components. It is recommended to use this method for data transmission among components in the project.

Of course, in addition to data, we can also pass methods between components

method

  1. Parent component calls child component: ref
  2. Child component calls parent component: emit

data

  1. Father to son: props
  2. Son to father: emit

Topics: Javascript Vue.js