Eight ways to implement communication in Vue

Eight ways to implement communication in Vue

1. Component Communication

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 are one-way binding (read-only properties): when the properties of the parent component change, they will be transmitted to the child component, but not vice versa)

The error message is probably: 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 the change of data subcomponent
<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.

  • Create a public bus.js file
  • Exposing the Vue instance
  • The data transmission party triggers bus.$emit (method name, transmitted data) through an event
  • The data receiver listens to the data through bus.$on(method name, [params]) in the life cycle function.
  • 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 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 prop to a component
  • Note: The parent slot receives the content as the outermost element and must have a slot-scope child element.
<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:
  }
})

This concludes this article about eight ways to use vue to build communications. For more information about how to use vue to build communications, please search previous articles on 123WORDPRESS.COM or continue browsing the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Details on how to write react in a vue project
  • Vue+element implements drop-down menu with local search function example
  • How to use wangEditor in vue and how to get focus by echoing data
  • Comparison of the advantages of vue3 and vue2
  • Vue realizes dynamic progress bar effect
  • Vue implements dynamic circular percentage progress bar
  • Vue realizes the percentage bar effect
  • How to implement draggable components in Vue

<<:  How to use mysqldump for full and point-in-time backups

>>:  Distinguishing between Linux hard links and soft links

Recommend

Vue.js implements music player

This article shares the specific code of Vue.js t...

Mysql anonymous login cannot create a database problem solution

Frequently asked questions Access denied for user...

Detailed explanation of Mysql's method of optimizing order by statement

In this article, we will learn about the optimiza...

How to set utf-8 encoding in mysql database

Modify /etc/my.cnf or /etc/mysql/my.cnf file [cli...

MySQL Server 8.0.13.0 Installation Tutorial with Pictures and Text

Install 8.0.13 based on MySQL 6.1.3. MySQL 8.0.13...

Summary of various methods for JS data type detection

Table of contents background What are the methods...

10 SQL statement optimization techniques to improve MYSQL query efficiency

The execution efficiency of MySQL database has a ...

Detailed explanation of upgrading Python and installing pip under Linux

Linux version upgrade: 1. First, confirm that the...

JavaScript common statements loop, judgment, string to number

Table of contents 1. switch 2. While Loop 3. Do/W...

Steps to install RocketMQ instance on Linux

1. Install JDK 1.1 Check whether the current virt...

How to manage multiple projects on CentOS SVN server

One demand Generally speaking, a company has mult...

Pure CSS to achieve the effect of picture blinds display example

First, let me show you the finished effect Main i...

Implementation of React star rating component

The requirement is to pass in the rating data for...