Eight examples of how Vue implements component communication

Eight examples of how Vue implements component communication

For Vue, message passing between components is very important. Here is my summary of the common ways of message passing between components:

1. Props parent component ---> child component communication

Parent component---property transfer to child component

Subcomponents---receive data in props mode

<Son :datas="fData"></Son>

<script>
import Son from '@/components/son'
  export default{
    name:'Father',
    components:{Son},
    data(){
      return {
        fData:'I am the value passed from the parent component to the child component - props method'
      }
    }
  }
</script>

The parameter name accepted by the child component props must be consistent with the property name defined when the parent component is passed

<template>
  <div>I am the data of the parent component: {{fData}}</div>
  <div @click=changeData>I am the parent component passing the modified data: {{mydata}}</div>
</template>
<script>
  export default{
    name:'Son',
    props:{
      fData:{
        type:String,
        default:''
      }
    }
    data(){
      mydata:this.fatherData
    },
    methods:{
     changeData(){
        this.mydata += 'Change data'
      }
    },
  }
</script>

Notice:

  • Child components cannot directly modify the values ​​passed by parent components: because of Vue's one-way data flow mechanism, if the value of the parent component is modified directly, it will be "polluted". (props is a one-way binding (read-only property): when the property of the parent component changes, it will be transmitted to the child component, but not vice versa)
    The error message is probably: Vue uses prop communication error: Avoid mutating a prop directly since the value will be overwritten whenever the parent
  • Solution: You can define a variable mydata in the subcomponent to receive fData data
  • If the parameter passing type is uncertain, you can write it like this:
props:{
    fData:{
        type:[String,Number],
        default:''
    }
}

2. $emit child component ---> parent component transfer

  • Subcomponent binding custom events
  • The first parameter of $emit() is: the custom event name, and the second parameter is: the data to be passed
  • Use $emit() to trigger changes to data

Subcomponents

<el-button @click="handleEmit">Change parent component</el-button>

<script>
 export default{
   name:'Son',
   methods:{
     handleEmit(){
       this.$emit('triggerEmit','subcomponent data')
     }
   }
 }
</script>

Parent component (the event name sent by the child component must be consistent with the event name accepted by the parent component)

<Son @triggerEmit="changeData"></Son>

<script>
 import Son from '@/components/son'
 export default{
   name:'Father',
   components:{Son},
   methods:{
     changeData(name){
       console.log(name) // => I am the data from the child component}
   }
 }
</script>

$emit and props combined with sibling components to pass values

  • The parent component introduces two child components
  • The parent component acts as a bridge

Parent Component

<childA :myName="name"></ChildA>
<ChildB :myName="name" @changeName="editName"></ChildB>  
    
export default{
  data() {
    return {
      name: 'Hello Data'
    }
  },
  methods: {
    editName(name){
      this.name = name
    }
  }
}

Subcomponent B changes and receives data

<p>Name: {{ myName }}</p>

<button @click="changeName">Change name</button>
    
<script>
export default{
  props: {
    myName:String
  },
  methods: {
    changeName() {
      this.$emit('changeName', 'new data name')
    }
}
}
</script>

Subcomponent A receives data

<p>Name: {{ newName }}</p>
    
<script>
export default{
  props: {
    myName:String
  }
}
</script>

3. Bus (Event Bus) Brother Component Communication

Transferring values ​​between components other than parent-child components or between components at more levels. In Vue, separate event centers are used to manage the transfer of values ​​between components.

  1. Create a public bus.js file
  2. Exposing the Vue instance
  3. The data transmission party triggers bus.$emit (method name, transmitted data) through an event
  4. The data receiver listens to the data through bus.$on(method name, [params]) in the life cycle function.
  5. Destruction event. On the receiving side, after the data is destroyed by bus.$off(method name), the data cannot be monitored.
import Vue from "vue"
const bus = new Vue()
export default bus

Define the call in the component that needs to change the data

<template>
  <div>
    <div>I am communication component A</div>
    <button @click="changeName">Change name</button>
  </div>
</template>

<script>
import bus from "@/utils/Bus.js";
export default {
  components: {},
  data() {
    return {};
  },
  mounted() {
    console.log(bus);
  },
  methods: {
    changeName() {
      bus.$emit("editName", "dataset!");
    },
  },
};
</script>

<style lang='scss' scoped>
</style>

The bus.js file is also introduced in another component, and the event callback is monitored through $on

<template>
  <div>
  <span>Name: {{name}}</span>
    <div>I am communication component B</div>
  </div>
</template>

<script>
import bus from "@/utils/Bus.js";
export default {
  components: {},
  data() {
    return {name};
  },
  mounted() {
    bus.$on("editName", (name) => {
        this.name=name
      console.log(name); // 
    });
  },
  methods: {},
};
</script>

<style lang='scss' scoped>
</style>

4. $parent, $children directly access component instances

  • The child component obtains the parent component instance through ---> $parent
  • The parent component obtains the child component instance array through ---> $children

Child component --- this.$parent can obtain the parent component's methods, data, etc., and can be used and executed directly

<template>
  <div>I am a child component</div>
</template>

<script>
export default{
  name:"Son",
  data(){
    return {
      sonTitle: 'I am the data of the child component'
    }
  },
  methods:{
    sonHandle(){
      console.log('I am a method of a subcomponent')
    }
  },
  created(){
    console.log(this.$parent)
    console.log(this.$parent.fatherTitle) // => I am the data of the parent component this.$parent.fantherHandle() // => I am the method of the parent component }
}
</script>

Parent component --- Gets the child component instance, and the instance obtained is in the form of an array. This.$children[0] can get a component instance and call component methods and data

<template>
  <div>
    <Son>I am the parent component</Son>
  </div>
</template>

<script>
import Son from './son.vue'

export default{
  name: 'father',
  components:{
    Son
  },
  data(){
    return {
      fatherTitle: 'I am the data of the parent component'
    }
  },
  methods:{
    fantherHandle(){
      console.log('I am the method of the parent component')
    }
  },
  mounted(){
    console.log(this.$children)
    console.log(this.$children[0].sonTitle) // => I am the data of the child component this.$children[0].sonHandle() // => I am the method of the child component }
}
</script>

5. $refs

ref is used to register reference information for an element or subcomponent. The reference information will be registered on the $refs object of the parent component.

The parent component uses $refs to get the component instance

<template>
  <div>
    <Son ref="son"></Son>
  </div>
</template>

<script>
import Son from './son.vue'

export default{
  name: 'father',
  components:{
    Son
  },
  mounted(){
    console.log(this.$refs.son) /*Component instance*/
  }
}
</script>

6. provide/inject (provide/inject) multi-component or deep component communication

Detailed explanation of provide/inject

  • The parent component uses provide to inject data
  • Subcomponents use inject to use data
/* Parent component */
export default{
 provide:
   return {
     provideName: 'Selling front-end'
   }
 }
}

At this point, the variable provideName can be provided to all its child components, including great-grandchildren, grandchildren, etc., and data can be obtained by simply using inject

/*Subcomponent*/
export default{
  inject: ['provideName'],
  created () {
    console.log(this.provideName) // => "Selling front-end"
  }
}
  • The parent component does not need to know which component uses the data it provides.
  • The sub-attachment does not need to know where the data comes from

7. slot (slot-scope scope slot) child element --> parent element (similar to communication)

  • Used as a reusable template (that can be passed data) to replace the rendered element
  • In the child component, just pass the data to the slot like you would pass a prop to a component
  • Note: The parent slot receives the content as the outermost element and must have the slot-scope attribute

Child Elements

<template>
  <div>
    <div class="isSon">
        <slot :info='arrList'></slot>
    </div>
  </div>
</template>

<script>
export default {
  components: {},
  data() {
    return {arrList:[1,'aa','张三']};
  },
  mounted() {
  },
  methods: {
    
  },
};
</script>

Parent element

<template>
<div>
    <SonG>
        <span slot-scope="props">
            <ul>
                aa
                <li v-for="item in props.info" :key="item">
                    {{item}}
                </li>
            </ul>
        </span>
    </SonG>
</div>
</template>

<script>

import SonG from '../components/SonG.vue'
export default {
   components:{
       SonG
   },
   data () {
       return {
       }
   }
}
</script>

8. Vuex state management

Equivalent to a public data warehouse

Provide some methods to manage warehouse data

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
  },
  mutations:
  },
  actions: {
  },
  modules:
  }
})

Summarize

This concludes this article about eight ways to implement component communication in Vue. For more relevant content about implementing component communication in Vue, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of seven component communication methods of Vue3
  • Three Vue slots to solve parent-child component communication
  • Details of 7 kinds of component communication in Vue3
  • Vue component communication method case summary
  • Detailed explanation of component communication in Vue (father-child component, grandfather-grandson component, brother component)
  • Several ways of communication between Vue components

<<:  How to set mysql to case insensitive

>>:  4 ways to view processes in LINUX (summary)

Recommend

Double loading issue when the page contains img src

<br />When the page contains <img src=&qu...

Implementing a random roll caller based on JavaScript

This article shares the specific code of JavaScri...

Interactive experience trends that will become mainstream in 2015-2016

The most important interactive design article in ...

MySQL 5.7.21 installation and configuration tutorial

The simple installation configuration of mysql5.7...

Summary of things to pay attention to in the footer of a web page

Lots of links You’ve no doubt seen a lot of sites ...

Dynamically add tables in HTML_PowerNode Java Academy

Without further ado, I will post the code for you...

JavaScript basics of this pointing

Table of contents this Method In the object Hidde...

HTTP and HTTP Collaboration Web Server Access Flow Diagram

A web server can build multiple web sites with in...

Analyzing the MySql CURRENT_TIMESTAMP function by example

When creating a time field DEFAULT CURRENT_TIMEST...

The phenomenon of margin-top collapse and the specific solution

What is margin-top collapse Margin-top collapse i...

MySQL million-level data paging query optimization solution

When there are tens of thousands of records in th...

Summary of Mysql-connector-java driver version issues

Mysql-connector-java driver version problem Since...

foreman ubuntu16 quick installation

Quickstart Guide The Foreman installer is a colle...